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:-

enter image description here

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..

1 Answer 1

2

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

No problem, glad to help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.