I have a problem when it comes to displaying the error messages of the form with ajax, by traditional http everything goes well but when I do it by ajax and I force an error in the form it tells me 422 Unprocessable Entity as a response but it does not show me the error messages as if it were normal http.
If the form is fine, continue with the controller code, I put a response below to check if it was received correctly by ajax and it did indeed respond to the message.
if ($request->ajax()) {
return response()->json(['mensaje'=>'validacion pasada wey']);
}
I reiterate, for normal http everything works fine and it shows me the corresponding validation messages, for example: name cannot be less than 3 characters.
I went through the documentation and quote this part: For a traditional HTTP request, a redirect response will be generated, while a JSON response will be sent for AJAX requests.
I leave my ajax code with which I have been testing the responses:
$('#btn_main').on('click',function(e){
e.preventDefault();
var action = $('#mainform').attr('action');
var method = $('#mainform').attr('method');
$.ajax({
beforeSend:function(){
console.log('before send ok');
},
url: action,
type: method,
data: $('#mainform').serialize(),
dataType:'json',
success:function(respuesta){
$.each(respuesta,function(name,value){
console.log('name: '+ name + '\n'+ 'value: '+ value);
});
},
error:function(jqXHR,estado,error){
console.log('estado error: ' + estado);
console.log('error de error: ' + error);
},
complete:function(jqXHR,estado){
console.log('estado complete: ' + estado);
},
timeout:10000
});
});
The way I am validating in the controller is as follows:
$this->validate($request,[
'tracking' => 'min:3',
'date' => 'min:6|required'
]);
Do I need to add something extra to the validation in the controller so that it gives me the corresponding response in json?
So I'm showing the errors but I guess if it gives me a json response I'll have to add them with jquery.
@if(count($errors)>0)
<ul class="alert alert-danger">
@foreach($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
@endif
I hope it helps or guides you:
It only prints the first error it finds
The problem was not the generation of the error messages since, as the documentation said, it returned them automatically.
The detail is that the messages arrive by XHR in responseJSON and to show them the error function would look like this: