在警报框中显示消息与ajax和json laravel

我有以下ajax代码:

$(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();
});
});
});

我在控制器中的代码:

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.']);
}

我发布我的ajax表单的路线是:

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

使用上面的代码,我可以通过ajax请求发送邮件 . 我想在我的视图中在警告框中显示json响应消息 . 但我无法这样做,因为json响应消息显示在白页中,我的帖子路径为url .

视图中的HTML代码:

<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

回答(2)

2 years ago

您的HTML中有一个简单的拼写错误:

id="'#ajax-inquire"

单引号 '# 都不应该存在,并且表示您的jQuery选择器与表单不匹配,因此您的Javascript实际上都没有触发 . 表单只是正常提交,因此您最终会使用 action 形式指定的URL .

id 应指定为:

id="ajax-inquire"

旁注:它不需要在现有的jQuery对象上使用 $() . 它的工作原理是因为jQuery接受jQuery对象作为选择器,但如果你没有以任何方式过滤或编辑选择器,那么它是多余的 .

// 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) {

2 years ago

尝试返回此而不是:

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

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

然后在你的视图中:

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