Reputation: 1
I have the following Ajax call to a rest web API:-
$.ajax({
url: "/********/getbytitle('****')/items",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
if(data.d != null){
//code goes here..
}
},
error: function (data) {
alert(data.error.message.value);
$("#customloader").hide();
}
});
where inside the error
section, i want to capture the error message value using alert(data.error.message.value);
, but i am getting the following error inside my browser console:-
data.error.message.value is undefined!!
although the JSON object have the following format:-
now as mentioned on the above picture, the error is returned if the user is not authorized. and our application will show username/password dialog box , when an unauthorized request is being received.. but i want to show the alert beside the username/pasword dialog box, with the json error message inside it..
Upvotes: 1
Views: 160
Reputation: 337550
The issue is because the first argument to the error
handler is the XHR object, not the parsed JSON response.
To make this work as you require you need to get the responseText
from the XHR yourself and parse it manually before attempting to read the value
property. Try this:
error: function(xhr) {
var data = JSON.parse(xhr.responseText);
console.log(data.error.message.value);
$("#customloader").hide();
}
Upvotes: 2