Reputation: 1151
Here is my error callback function from an ajax call.
error: function(xhr, status, error) {
var responseObj = jQuery.parseJSON( xhr.responseText );
}
From that I am sending this to the console:
console.log(responseObj.message);
Which is returning this:
Object {Invalid or missing parameters: Object}
Invalid or missing parameters: Object
email_already_in_use: "'Email' already in use"
If I stringify the response like this:
var responseMsg = responseObj.message;
if(typeof responseMsg =='object') {
var respObj = JSON.stringify(responseMsg);
console.log(respObj);
}
I get this:
{"Invalid or missing parameters":{"email_already_in_use":"'Email' already in use"}}
How can I print to the user that their email is already in use?
complete callback function:
error: function(xhr, status, error) {
var responseObj = jQuery.parseJSON( xhr.responseText );
var responseMsg = responseObj.message;
if(typeof responseMsg =='object') {
var respObj = JSON.stringify(responseMsg);
console.log(respObj);
} else {
if(responseMsg ===false) {
console.log('response false');
} else {
console.log('response something else');
}
}
console.log(responseObj.message);
}
Upvotes: 1
Views: 904
Reputation: 143
You could do something like this:
var errorMessages = responseObj.message["Invalid or missing parameters"];
for (var key in errorMessages) {
if(errorMessages.hasOwnProperty(key)){
console.log(errorMessages[key]);
}
}
If you have different kinds of messages (not only "Invalid or missing parameters"), you should iterate the message array first:
var errorMessages = responseObj.message;
for (var errorType in errorMessages){
if(errorMessages.hasOwnProperty(errorType)){
console.log(errorType + ":");
var specificErrorMsgs = errorMessages[errorType];
for (var message in specificErrorMsgs) {
if(specificErrorMsgs.hasOwnProperty(message)){
console.log(specificErrorMsgs[message]);
}
}
}
}
Upvotes: 3