I have a registration form for people. I need to send it with Ajax to not reload the page.
So far, I have the following ready that I followed for a tutorial.
Sending Js.
$("form#pessoasCadastrar" ).submit(function( event ) {
event.preventDefault();
data = $("form#pessoasCadastrar" ).serialize(),
url = '/pessoas/salvar',
var posting = $.post( url, { formData: data } );
posting.done(function( data ) {
if(data.fail) {
$.each(data.errors, function( index, value ) {
var errorDiv = '#'+index+'_error';
$(errorDiv).addClass('required');
$(errorDiv).empty().append(value);
});
$('#successMessage').empty();
}
if(data.success) {
$('.register').fadeOut(); //hiding Reg form
var successContent = '<div class="message"><h3>Registration Completed Successfully</h3><h4>Please Login With the Following Details</h4><div class="userDetails"><p><span>Email:</span>'+data.email+'</p><p><span>Password:********</span></p></div></div>';
$('#successMessage').html(successContent);
} //success
}); //done
});
PersonaRequest.php
public function rules(){ ... }
public function messages(){ .... }
public function response(array $errors)
{
if ($this->ajax() || $this->wantsJson())
{
return response()->json($errors, 422);
}
$dados = array('fail' => true, 'errors' => $errors);
return response()->json(array('fail' => true,'errors' => $errors));
}
PersonController.php
public function salvar(PessoaRequest $request){
$p = new Pessoa();
[....]
return Response()->json(array('success' => true,$request->all()));
}
When submitting the form, if it does not fill in the input, it falls on a white screen with the json return of the PersonRequest, stating which fields are to be filled. If it succeeds to send, it gives the json return of success.
My problem is when it gives the error in the request, I would like to get the json return and treat in my view to show the errors, but whenever I send it, it falls on that white screen with the errors
{"fail":true,"errors":{"nome":["O campo nome \u00e9 obrigat\u00f3rio!"]}}
How do I get these info in my view without reloading it?