Quiet Man Quiet Man - 24 days ago 12
jQuery Question

how to make validation using ajax Laravel 5.3

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.

Answer

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!