List errors returned in an ajax request

Asked

Viewed 96 times

2

I have a Controller that is returning errors this way:

return response()->json(['erros' => $this->renderHttpException($e)]);

I am receiving this json as a response to the ajax request:

{"email":["The email field is required."],"telefone":["The telefone field is required."]}

I need to list these errors in a div, without having to specify each field as I did with the email, as I do?

function Create(id, url) {
    $.ajax({
        url: url,
        data: $('#' + id).serialize(),
        dataType: 'json',
        type: 'POST',
        error: function (data) {
            var errors = data.responseJSON;
            document.getElementById('message').innerHTML = errors.email;
        }
    });
}
  • Place the ajax call.

  • I put the call ajax @rray

  • When Windows sends the error msg always from Undefined? tried to change the error: for done: and in that change check if the object has any message?

  • It’s just data.email and data.telefone

  • I was able to pick up with this: var errors = data.responseJSON; and putting errors.email for example. But now how do I make him run json without I have to specify the field? Because there are many, I put 2 here to simplify

  • I edited the question for the current situation

Show 1 more comment

1 answer

3


Use the each to browse the JSON

$.ajax({
    url: url,
    data: $('#' + id).serialize(),
    type: 'POST',
    success: function (data) {
       $.each(data, function(i,v){
          $('#message').append('<span>'.v.'</span><br>');
       });
    }
});
  • 2

    I got it this way @Gumball, suggested some small editions to stay the same way I put it here, vlw!

Browser other questions tagged

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