how to make validation using ajax Laravel 5.3

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-24 09:28:47

问题


I am using Laravel 5. In my OrganisationsController I have a method addItem

 public function addItem(Request $request)
    {
        $rules = array(
            'nom' => 'required',
        );
        // for Validator
        $validator = Validator::make(Input::all(), $rules);
        if ($validator->fails())
            return Response::json(array('errors' => $validator->getMessageBag()->toArray()));

        else {
            $section = new Section();
            $section->nom = $request->nom;
            $section->save();
            return response()->json($section);
        }
    }

Ajax code

    $("#add").click(function() {
            $.ajax({
                type: 'post',
                url: '/addItem',
                data: {
                    '_token': $('input[name=_token]').val(),
                    'nom': $('input[name=nom]').val()
                },
                success: function(data) {
                    if ((data.errors)) {
                        $('.error').removeClass('hidden');
                        $('.error').text(data.errors.title);
                        $('.error').text(data.errors.description);
                    } else {
                        $('.error').remove()
                        $('table').append("<tr class='section" + data.id + "'><td>" + data.id + "</td><td>" + data.nom + "</td><td><button class='edit-modal btn btn-info' data-id='" + data.id + "' data-nom='" + data.nom + "'><span class='glyphicon glyphicon-edit'></span> Edit</button> <button class='delete-modal btn btn-danger' data-id='" + data.id + "' data-nom='" + data.nom +  "'><span class='glyphicon glyphicon-trash'></span> Delete</button></td></tr>"); }
                   }
                });

            $('#noom').val('');
        });

html code

<div class="form-group row add">
    <div class="col-md-5">
        <input type="text" class="form-control " id="noom" name="nom"
               placeholder="New section here" required>
		<p class="error text-center alert alert-danger hidden"></p>
    </div>
    <div class="col-md-2">
        <button class="btn btn-warning" type="submit" id="add">
            <span class="glyphicon glyphicon-plus"></span> Add new Section
        </button>
    </div>

</div>

I don't know why my validation not work. Please suggest a example for this. I am using laravel 5. I have searched so many sites. But I cannot get solution for this.


回答1:


If your validations fails it will return with a status code (error code) of 422.

In your $.ajax you're only using success which won't be called if your validation fails.

You will need to add an error method to your ajax options. Using your above code you would have something like:

success: function (data) {
    $('.error').remove()
    $('table').append("<tr class='section" + data.id + "'><td>" + data.id + "</td><td>" + data.nom + "</td><td><button class='edit-modal btn btn-info' data-id='" + data.id + "' data-nom='" + data.nom + "'><span class='glyphicon glyphicon-edit'></span> Edit</button> <button class='delete-modal btn btn-danger' data-id='" + data.id + "' data-nom='" + data.nom + "'><span class='glyphicon glyphicon-trash'></span> Delete</button></td></tr>"); 
},
error: function (data) {
    if (data.errors) {
        $('.error').removeClass('hidden');
        $('.error').text(data.errors.title);
        $('.error').text(data.errors.description);
    }
}

Hope this helps!




回答2:


the solution is remove the condition if(data.errors)




回答3:


for jquery 3 and above, use this code

$.ajax({
      type: 'post',
      url: '/addItem',
      data: {
           '_token': $('input[name=_token]').val(),
           'nom': $('input[name=nom]').val()
}).done(function(data){
      //if success, do this
      console.log(data);
      alert('success');
}).fail(function(jqXHR){
      if (jqXHR.status == 422) {
             var errors = (jqXHR.responseJSON);
             console.log(errors);
      }
});


来源:https://stackoverflow.com/questions/40422363/how-to-make-validation-using-ajax-laravel-5-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!