How to return ajax errors with jquery in Laravel 5.6

Asked

Viewed 719 times

0

From what I read in the documentation, when using ajax, the answer is always returned in json, but I cannot receive the information to print.

The message returned on 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 the 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();
}
  • Already tried to access via data.message?

  • I tried yes, I also tried with responseJSON, which I saw in other tips, but it’s like it’s killing the application.

2 answers

1

Here I leave it in case it suits some novice like me what I got: I adapted this code based on this tip: https://www.jesseqli.com/using-ajax-in-laravel-5-form-request-error-handling/

$(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);
                    });
                }
            }
        });
    });
});

0

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

First check the data that is sent via ajax:

  • They are being sent?
  • Are correct to be validated?

(Do not forget that for ajax requests it is necessary that the token is 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 in your controller and try to return the data via json in the controller right after validation:

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

On your return Json can put only:

console.log(data);

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

You can get more details about ajax calls errors by the following:

success: function( conteudo ) {
    console.log(conteudo);
},
error: function(jqXHR, textStatus, errorThrown){
    console.log(jqXHR + " - " + jqXHR.getResponseHeader() + " - " + textStatus + " - " + errorThrown + " - " + errorThrown.message);
}
  • 1

    Thanks for the help, answering your question, I created the "error" purposely to know what the behavior of Laravel and also not to have to watch all the time on the console, while it is in development. What I realized is that when they are validation errors using the Laravel validator, it always returns json vectors through responseJSON ajax, but when there are several errors of sql for example, it returns json, but without being by vector through the responseText. I will post the solution I arrived at to facilitate development, using jquery or javascript.

  • I usually force the errors in these cases tbm, in case it is not ajax I use dd(); that helps a lot.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.