Reputation: 7390
As part of a JQuery AJAX POST request which invokes an API, I am trying to create a new item.
I'm trying to print the exact error message in case an item with the same name already exists. The appropriate error response is returned from the API call based on success/failure.
I'm somehow not able to extract the exact this error message which is returned as part of the API call. What I just want to know is how exactly can I extract this error message, which I can display as a flash message in the UI.
On doing a console.log(data), I get the below printed in Firebug as part of the response:-
data: Object { readyState=4, responseText="{"error":"Item already exists","status":404}", status=404, more...}
On expanding the entire response(on click of "more...") . I get the following:-
readyState
4
responseText
"{"error":"Item already exists","status":404}"
status
404
statusText
"Not Found"
abort
function()
always
function()
complete
function()
done
function()
error
function()
fail
function()
getAllResponseHeaders
function()
getResponseHeader
function()
overrideMimeType
function()
pipe
function()
progress
function()
promise
function()
setRequestHeader
function()
state
function()
statusCode
function()
success
function()
then
function()
Now to print the above message, I tried the following:-
var obj = data.responseText
console.log("Object Error:- ", obj.error);
But console.log("Object Error:- ", obj.error);
returned undefined
in Firebug. I understand I am not directly dealing with a Hash. responseText has a hash within a string, and I'm sure the answer to my question is somehow related to this observation.. . How exactly can I extract the exact error message ?
Upvotes: 0
Views: 187
Reputation: 10517
Your response text is JSON. You need to parse it and work with a result as a plain JS object.
JSON.parse(data.responseText).error
Upvotes: 0