I'm using PHP to submit a form and then use $.ajax(). Here is my $.ajax method, which works flawlessly when it is successful. When I want to display mistakes, it is difficult to loop over every responseText. See the following $.ajax() code:
$.ajax({
// ... ,
error: function(errors){
$.each(errors, function(index, error){
info.hide().find('ul').append('<li>'+error+'</li>');
});
info.slideDown();
}
});
I detect all problems, but I'm confused about how it displays just errors. See my output on the screen at http://prntscr.com/7nt3lq. I only want to display the following error fields: If I put it as: "name":["The name field is required."],"fname":["The fname field is required."]
error: function(errors){
console.log(errors);
}
Then the screen output is http://prntscr.com/7nt9tv. With a loop through, how can I eliminate the exceptional error 422 (Unprocessable Entity) and retrieve just the responseText?
The problem is the first param to the error
callback is not the respose
data, it is the jqXHR
object.
$.ajax({
url: '/echo/asdf',
// ... ,
error: function (jqxhr) {
if (jqxhr.status = 422) {
var errors = JSON.parse(jqxhr.responseText);
$.each(errors, function (index, error) {
info.hide().find('ul').append('<li>' + error + '</li>');
});
info.slideDown();
}
}
});