I was looking at Benjamin Gruenbaum's answer, where he prints result in the body of the HTML. While he does talk extensively, him and other answers about how this works, they do not directly answer the question that is How do I return the response from an asynchronous call?
As I understand it, he (and I) wanted to be able to return the result and assign it to a variable for instance, or console.log() it outside the function foo.
Here is the code:
foo(function (result) {
document.body.innerHTML = result;
});
function foo(callback) {
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function () {
if (httpRequest.readyState === 4) { // request is done
if (httpRequest.status === 200) { // successfully
callback(httpRequest.responseText); // we're calling our method
}
}
};
httpRequest.open('GET', "someFile.json");
httpRequest.send();
}
What I really want is to read the file "someFile.json" and store the corresponding string in a variable jsonString instead of assigning it to the body of the page, so I can do something with it somewhere else.