How to return ajax errors with jquery in Laravel 5.6

0

As I read in the documentation, when using ajax, the answer is always returned in json, but I can not get the information to print.

The message returned in the console is:

http://localhost/projeto/cadastra/usuario 422 (Unprocessable Entity)

and the details

{message: "The given data was invalid.", errors: {email: ["validation.unique"]}}
errors:{email: ["validation.unique"]}
message:"The given data was invalid."

and my ajax code is:

$('#cad_usu').on('submit',function(e){
    e.preventDefault();                    
    $.ajax({
        url: "{{ url('cadastra/usuario') }}",
        data: $(this).serializeArray(), //$(this).serialize() tentei tbm
         type: 'post',
         dataType: 'json',
         success: function(data){
             console.log(data.message);                                                         
             $('#retorno').html(data.message); //data.responseJSON tentei tbm
          }
    });
});

missing controller

public function cadastra(Request $request)
{
    $request->validate([
        'nome' => 'required|max:55',
        'email' => 'required|unique:usuarios',
        'senha' => 'required',
    ]);

    $c = new Usuario();
    $c->nome = $request->nome;
    $c->email = $request->email;
    $c->senha = Hash::make($request->senha);
    $c->save();
}
    
asked by anonymous 05.06.2018 / 16:05

2 answers

0

By its error message in return json it seems that the email is a unique key defined as validation form email: ["validation.unique"]

First check the data that is sent via ajax:

  • Are they being sent?
  • Are they correct to be validated?

(Note that for ajax requests the token must be correct in the request)

You can check the data as follows:

Add: console.log($(this).serializeArray()); before making the ajax request and check the data in the browser console.

Second, check the data validation rule on your controller and try to return the data via json to the controller shortly after doing the validation:

return response()->json($request->all());

On your return Json can only put:

console.log(data);

Another detail you can check is your route file, the link passed in ajax is set to POST?

You can have more details about ajax call errors with the following:

success: function( conteudo ) {
    console.log(conteudo);
},
error: function(jqXHR, textStatus, errorThrown){
    console.log(jqXHR + " - " + jqXHR.getResponseHeader() + " - " + textStatus + " - " + errorThrown + " - " + errorThrown.message);
}
    
05.06.2018 / 21:37
0

Here I leave it up to serve some newbie like me what I got: I adapted this code based on this tip: link

$(document).ready(function(){
    $('#xx').on('submit',function(e){
        e.preventDefault();

        /*$.ajaxSetup({ //parte opcional, recomendada pela documentação do Laravel
            headers: {
                'X-CSRF-TOKEN': $('meta[name='csrf-token']').attr('content')
            }
        });*/

        $.ajax({
            url: '{{ url('xx') }}
            data: $(this).serialize(),
            type: 'post',
            dataType: 'json',
            //processData: false,
            //contentType: false,
            success: function(data){
                //console.log(data);
                $('#suc').html(data);
            },
            error: function( data )
            {
                if(!data.responseJSON){
                    console.log(data.responseText);
                    $('#err').html(data.responseText);
                }else{
                    $('#err').html('');
                    $.each(data.responseJSON.errors, function (key, value) {
                        $('#err').append(key+": "+value+"<br>");
                        //console.log(key);
                    });
                }
            }
        });
    });
});
    
06.06.2018 / 22:25