0

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('[email protected]')->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

3
  • use JSON.parse(response). Commented Oct 13, 2017 at 7:32
  • Your code works fine for me. Show us the minimum relevant part of your HTML. Commented Oct 13, 2017 at 8:19
  • @KetanModi your suggestion is also isn't helping. Commented Oct 13, 2017 at 10:48

2 Answers 2

1

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) {
Sign up to request clarification or add additional context in comments.

6 Comments

jQuery was still able to pickup the id and make ajax request with typo mistake.
Fixed the typo mistake. Sill same white screen with json message.
@TanjaForsberg sorry - 1 more thing wrong with that id. I Updated my question. BTW - I am 100% sure that the AJAX request is not happening, just a normal POST. The POST is not the same as AJAX - one (AJAX) happens asynchronously, without the page changing, but a plain POST will redirect you to the new page.
Thank for suggestion. I fixed the typos. Removed action and method attribute from the form. It is working fine.
Great, glad to help - but you don't need to remove action and method. That's not part of this problem.
|
0

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']}}

1 Comment

Returning a new view is not what OP is trying to do. This does not answer her question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.