List errors returned in an ajax request

2

I have a Controller that is returning errors like this:

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

I'm getting 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, how do I?

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;
        }
    });
}
    
asked by anonymous 23.09.2016 / 20:30

1 answer

3

Use each to traverse JSON

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