简体   繁体   English

Laravel 5.2:如何在使用ajax提交表单时显示验证错误?

[英]Laravel 5.2:How to show validation errors when submitting form with ajax?

I am using laravel 5.2,my question is: 我正在使用laravel 5.2,我的问题是:
How to show validation errors when submitting form with ajax ? 使用ajax提交表单时如何显示验证错误?

For example: 例如:
When ajax is not used,if the title field is not filled in, when submitting,there is an information : 如果未使用ajax,如果未填写标题字段,则在提交时会有以下信息:
"The title field is required." “标题字段是必需的。”
And, when ajax is used,how to show the information above. 并且,当使用ajax时,如何显示上面的信息。

View: 视图:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link href="https://cdn.bootcss.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.bootcss.com/tether/1.1.1/css/tether.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
    <form id="formArticle" class="form-horizontal" role="form">
        <fieldset class="row form-group">
            <label class="col-xs-2 control-label">Title:</label>
            <div class="col-xs-10">
                <input id="title" name="title" type="text" class="form-control"
                       value="{{ old('title') }}">
                <span class="help-block"><strong></strong></span>
            </div>
        </fieldset>

        <fieldset class="row form-group">
            <label class="col-xs-2 control-label">Content:</label>
            <div class="col-xs-10">
                <input id="content" name="content" type="text" class="form-control"
                       value="{{ old('content') }}">
                <span class="help-block"><strong></strong></span>
            </div>
        </fieldset>

        <fieldset class="row form-group">
            <label class="col-xs-2 control-label" for="photo">Photo:</label>
            <div class="col-xs-10">
                <input id="photo" name="photo" type="file" class="form-control-file">
                <span class="help-block"><strong></strong></span>
            </div>
        </fieldset>
        <fieldset class="form-group">
            <div class="col-xs-12">
                <button id="submit" type="submit" class="btn btn-primary">Submit</button>
            </div>
        </fieldset>
    </form>
    <div class="alert alert-success" role="alert" hidden>
        upload successfully
    </div>
</div>
<script src="https://cdn.bootcss.com/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/tether/1.1.1/js/tether.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/4.0.0-alpha.2/js/bootstrap.min.js"></script>

</body>
</html>

Javascript: 使用Javascript:

<script>
    $(function () {
        var articleData = new FormData($('#formArticle')[0]);


        $(document).on('submit', '#formArticle', function (e) {
            e.preventDefault();

            $('input+span>strong').text('');
            $('input').parent().parent().removeClass('has-error');

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            $.ajax({
                        type: "POST",
                        url: "{{ url('article/') }}",
                        dataType: 'json',
                        processData: false,
                        contentType: false,
                        cache: false,
                        data: articleData
                    })
                    .done(function (data) {
                        $(".alert-success").prop("hidden", false);
                    })
                    .fail(function (data) {
                        $.each(data.responseJSON, function (key, value) {
                            var input = '#formArticle input[name=' + key + ']';
                            $(input + '+span>strong').text(value);
                            $(input).parent().parent().addClass('has-error');
                        });
                    });
        });
    });
</script>

Controller: 控制器:

    public function store(Requests\StoreArticleRequest $request)
    {
        $article = new Article;
        $article -> user_id = \Auth::id();

        $article->title = $request->title;
        $article->content = $request->content;

        $photo = $request->photo;
        $destinationPath = 'uploads/';
        $extension = $photo->getClientOriginalExtension();
        $photoName = \Auth::user()->id . '_' . time() . '.' . $extension;
        $photo->move($destinationPath, $photoName);
        $article -> photo = '/'.$destinationPath.$photoName;

        $article->save();
    }

StoreArticleRequest: StoreArticleRequest:

public function rules()
    {
        return [
            'title'=>'required',
            'content'=>'required',
            'photo'=>'required'
         ];
    }

Form data can be saved to database successfully if inputs are filled in completely. 如果输入完全填写,表单数据可以成功保存到数据库。
But, when they are not filled in completely,or filled in nothing, 但是,当它们没有被完全填满,或者什么都没有填满时,
json message is shown in Chrome debugger's Preview and Response tags, like this: json消息显示在Chrome调试器的预览和响应标记中,如下所示:

{
"title":["The title field is required."],
"content":["The content field is required."],
...
}

But, the message can not be shown in html. 但是,消息无法在html中显示。
And ,at this time, ".alert-success" is shown. 而且,此时,显示".alert-success"
I don't know where the problems are in my code. 我不知道代码中的问题在哪里。

I think my understanding to done() and fail() is not right. 我认为我对done()和fail()的理解是不对的。
done() and fail() mean that ajax request is done or failed, done()和fail()表示ajax请求已完成或失败,
but not validation successful or failed, 但验证不成功或失败,
no matter validation of laravel is successful or failed, 无论laravel验证成功还是失败,
ajax request is done, ajax请求完成,
so, 所以,
even though I don't complete the inputs, 即使我没有完成输入,
div class="alert alert-success" always appears . 总是出现div class =“alert alert-success”。

You're getting the success message because done() is fired when a "good" response is received. 您收到成功消息,因为收到“好”响应时会触发done() While you're getting error messages, the actual response from the server is still a 200 . 当您收到错误消息时,服务器的实际响应仍为200

You'd want to check the data in done() to make sure it isn't an error. 您需要检查done()data以确保它不是错误。 If title === "The title field is required." 如果title === "The title field is required." , you'd want to run the code that is currently in your fail() . ,你想要运行当前在fail()的代码。

.done(function (data) {
  if(data.title[0] == 'The title field is required.' ) {
    alert('Title is required');
  }
  else {
    $(".alert-success").prop("hidden", false);
  }
})
.fail(function (data) {
  alert('The server failed somewhere');
});

Obviously, you'd want to do something other than alerts, and you'd want to check both fields, but that's the gist of it. 显然,你想要做除警报以外的其他事情,并且你想要检查两个字段,但这是它的要点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM