Hi I am using laravel jQuery & ajax to return a JSON error as so:
error: function (jqXhr, json, errorThrown) {
var errors = JSON.stringify(jqXhr.responseJSON);
var errorsHtml= '';
$.each( errors, function( key, value ) {
errorsHtml += '<li>' + value[0] + '</li>';
});
toastr.error( errorsHtml , "Error " + jqXhr.status +': '+ errorThrown);
}
However I get the following error:
Uncaught TypeError: Cannot use 'in' operator to search for '209' in {"errors"{"name":["A name is required"],"hours":["Please input a capacity in hours."],"start_date":["Please input a start date."],"end_date":["Please input an end date."]}}
Any ideas, if I use .parse
instead of .stringify
i get the following error:
Uncaught SyntaxError: Unexpected token j
.
Any ideas what I'm doing wrong??
Thanks in advance.
edit
var errors = JSON.stringify(jqXhr.responseJSON);
console.log('normal'+jqXhr.responseJSON);
console.log('stringify: '+errors);
normal[object Object]
stringify: {"errors":{"name":["A name is required"],"hours":["Please input a capacity in hours."],"start_date":["Please input a start date."],"end_date":["Please input an end date."]}}
You should use:
jqXhr.responseJSON
is the response already parsed into an object. The JSON you show in the edit will be an object with one property named "errors". You want to loop through the key/values of that property.