I have a JavaScript function that receives data from an AJAX call to the server.
function dataReceiver() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
// Everything is good, the response was received.
if (httpRequest.status === 200) {
//console.log( JSON.parse(this.responseText) );
let data = JSON.parse(this.responseText);
console.log("1) " + data["key1"]);
console.log("2) " + data['key1']);
console.log("3) " + data.key1);
} else {
// There was a problem with the request.
alert("Error: HTTP request status " + httpRequest.status);
}
} else {
// Not ready yet.
console.log("Request status: " + httpRequest.status);
}
}
The data is sent in JSON format, and it is being received correctly. The commented console.log() line returns
{"key1": "stringValue1", "key2": "stringValue2", "key3": intValue}
with keys and values exactly as expected.
However, I cannot access this data. The three uncommened console.log() lines show the ways I've tried to get access to this data, and the console shows
- undefined
- undefined
- undefined
How do I access JSON data returned by an AJAX request?
There are several other questions on this site with similar problems, but all that I can find involve things that don't apply to this situation, like React, jQuery, or PHP. This is plain JavaScript.
Edit: If I don't try parsing the JSON, the raw response comes back as
console.log( this.responseText );
-> "{\"key1\": \"stringValue1\", \"key2\": \"stringValue2\", \"key3\": intValue}"
which is just the expected JSON object with escape backslashes for the double-quotes.