使用ajax和json laravel在警告框中显示消息

使用ajax和json laravel在警告框中显示消息

问题描述:

I have the following ajax code:

$(function() {
// Get the form.
var form = $('#ajax-inquire');

// Get the messages div.
var formMessages = $('#form-messages');


// Set up an event listener for the contact form.
$(form).submit(function(event) {
// Stop the browser from submitting the form.
event.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();

// Submit the form using AJAX.
$.ajax({
    type: 'POST',
    url: $(form).attr('action'),
    data: formData
})
.done(function(response) {
    // Make sure that the formMessages div has the 'success' class.
    formMessages.removeClass('alert-danger');
    formMessages.addClass('alert-success');

    // Set the message text.
    $(formMessages).text(response.success);

    // Clear the form.
    $('#fullName').val('');
    $('#email').val('');
    $('#telephone').val('');
    $('#message').val('');
    formMessages.show();
})
.fail(function(data) {
    // Make sure that the formMessages div has the 'error' class.
    formMessages.removeClass('alert-success');
    formMessages.addClass('alert-danger');

    // Set the message text.
    if (data.responseText !== '') {
        $(formMessages).text(data.responseText);
    } else {
        $(formMessages).text('Oops! An error occured and your inquire could not be sent.');
    }
    formMessages.show();
});
});
});

And my code in controller:

    public function postInquire(Request $request)
{
    $data = array(
        'tripName' => $request->tripName,
        'fullName' => $request->fullName,
        'email' => $request->email,
        'telephone' => $request->telephone,
        'bodyMessage' => $request->message
    );

    Mail::to('mail@domain.com')->send(new TourInquire($data));
    return response()
     ->json(['code'=>200,'success' => 'Your inquire is successfully sent.']);
}

And my route for posting my ajax form is:

Route::post('/inquire', 'PostPublicController@postInquire')->name('postInquire');

With the above codes I'm able to send mail via ajax request. I'm trying to show json response message in alert box in my view. But I'm unable to do so as json response message is show in white page with url of my post route for form.

HTML code in view:

<div class="modal-body">
                <div id="form-messages" class="alert success" role="alert" style="display: none;"></div>
                <div class="preview-wrap">

                    <img src="{{asset($tour->featuredImage->path)}}" class="preview-img thumbnail" alt="{{$tour->featuredImage->name}}">
                    <div class="form-wrap">
                        <form action="{{route('postInquire')}}" id="'#ajax-inquire" method="POST">
                            {{csrf_field()}}
                            <div class="form-group">
                                <input type="hidden" name="tripName" id="tripName" value="{{$tour->title}}">
                                <label>Name</label>
                                <input type="text" class="form-control" placeholder="Enter Your Full Name" name="fullName" id="fullName" required>
                            </div>
                            <div class="form-group">
                                <label>Email</label>
                                <input type="email" class="form-control" placeholder="Email Address" name="email" id="email" required>
                            </div>
                            <div class="form-group">
                                <label for="telephone">Phone</label>
                                <input type="tel" class="form-control" placeholder="Phone Number" name="telephone" id="telephone" required>
                            </div>
                            <div class="form-group">
                                <label for="message">Message</label>
                                <div class="row">
                                    <textarea name="message" id="message" cols="30" rows="5" class="form-control"></textarea>
                                </div>
                            </div>
                            <button class="btn btn-primary hvr-sweep-to-right">Send Message</button>
                        </form>
                    </div>
                </div>
            </div>

enter image description here

You have a simple typo in your HTML:

id="'#ajax-inquire" 

Both the single quote ' and the # should not be there, and mean that your jQuery selector does not match the form, so none of your Javascript is actually firing. The form is simply submitting normally, and so you end up on the URL specified in the form action.

The id should be specified like:

id="ajax-inquire" 

Side note: It doesn't technically matter but you don't need to use $() on existing jQuery objects. It works because jQuery accepts a jQuery object as a selector, but it is redundant if you are not filtering or editing the selector in any way.

// Here you set form as a jQuery object
var form = $('#ajax-inquire');

// You don't need "$(form)" here, "form" is all you need
$(form).submit(function(event) {

// You can simply use the existing jQuery object
form.submit(function(event) {

Try to return this instead this:

$your_json= json_encode(['code'=>200,'success' => 'Your inquire is successfully sent.']);

return view('your_view',compact('your_json'));

and then in your View:

{{json_decode($your_json)['success']}}