Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check AJAX Response String when type is set to JSON

I am using ajax to get JSON data from a web page. So I have set responseType to be json. If the web page processes the data successfully, it returns a valid JSON string, which is fine.

But if the web page fails, it returns a JSON string with error message inside, (sorry for the misunderstanding,) it returns an error string, not a json string, so JavaScript does not recognize it as valid JSON string. So if I check for response, it is null. In that case, I want to see the response string and check what the error message is.

var xhr = new XMLHttpRequest();
xhr.responseType = "json";
xhr.open("POST", "/someEndpoint");
xhr.send();
xhr.onload = function() {
    console.log(xhr.response);
}

(Fiddle to reproduce the issue.)

If /someEndpoint returns valid JSON, xhr.response is a JavaScript object. However, if it's not valid JSON (as when the endpoint responds with an error message), then I get an empty object in xhr.response. I can't access the invalid-JSON error response, because accessing xhr.responseText gives the error:

Uncaught DOMException: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'json')

I don't know how to read the original HTTP response after I've run the request with responseType="json", since responseText cannot be accessed.

like image 315
BigName Avatar asked Oct 19 '25 11:10

BigName


1 Answers

With your code the way it is currently this will not work as the error message directly indicates:

Uncaught InvalidStateError: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'json').

As you can see with the following proof:

var xhr = new XMLHttpRequest();
//xhr.responseType = "json";

xhr.open("POST", "/echo/json/");
xhr.send("hello world");

xhr.onload = function() {
    console.log(xhr.response);
    console.log(xhr.responseText);
}

When you set the responseType to JSON you will not get a responseText property on the object. You will want to NOT set the responseType and evaluate the response (parseJSON) as a text string. If you have an error message for the response then your eval will fail to parse the JSON properly. This is alot like what jQuery does under the hood, and on that topic...

Why fight with the improbable task of working with the native XMLHttpRequest browser object. jQuery has spend years normalizing AJAX across browsers and standardizing an API. That API has an 'always' call back that will fit your needs perfectly.

TLDR use jQuery for this and save the headaches.

like image 191
MattSizzle Avatar answered Oct 21 '25 08:10

MattSizzle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!