Showing request validation errors when submitting form by ajax
Hey everyone,
I'm writing a new project in Laravel 5 and submitting a form by ajax and I'm using a request to validate the form.
I can't quite figure out how to grab the error message data using javascript if the validation fails. As it mentions in the documentation: "If the incoming request was an ajax request, no redirect will be generated. Instead, an HTTP response with a 422 status code will be returned to the browser containing a JSON representation of the validation errors." - http://laravel.com/docs/5.0/validation#controller-validation
Any ideas how I can get access to the data returned to the browser if a validation error occurred?
If an ajax request don't pass a form request validation, errors will be returned as json. You can catch them in the error callback of jquery ajax method :
$.ajax({
url: URL,
type: 'PUT',
data: formdata,
success: function (response) {
window.location = "{{ URL::route('campaign.index')}}";
},
error: function(xhr,status, response) {
var error = jQuery.parseJSON(xhr.responseText); // this section is key player in getting the value of the errors from controller.
var info = $('.edit_alert');
info.hide().find('ul').empty();
for(var k in error.message){
if(error.message.hasOwnProperty(k)){
error.message[k].forEach(function(val){
info.find('ul').append('<li>' + val + '</li>');
});
}
}
info.slideDown();
}
});
error: function(data)
{
var errors = '';
for(datos in data.responseJSON){
errors += data.responseJSON[datos] + '<br>';
}
$('#response').show().html(errors); //this is my div with messages
}
So, when the request fails, the error method prints the messages from Laravel Validation system on my div .
If your endpoint is not understanding that it's an ajax request it may be returning a redirect back with the errors instead of a failed response back with the errors as json.
You might be best creating your own question with the code you're using.