I am learning the basics of AJAX, and I am trying to store the result of the call in a variable. I have a data.txt file with this object:
[
{ "id": "5688","name": " Jorge Luis Borges"},
{ "id": "5799","name": " Lewis Carroll"}
]
And I am calling it with this call:
var object = "No object";
function requestFunction(url){
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.addEventListener("load", function() {
object = this.response;
});
request.send(null);
return object;
};
console.log(requestFunction("data.txt"));
I don't know why, but result = this.response
doesn't affect to the variable where I want to store the result, and the console outputs its original value: No object
.
Any idea why?
EDIT: I have been reading the fantastics responses in How do I return the response from an asynchronous call?, and I updated the function to include a callback that, when called, output the result:
function requestFunction(url){
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.addEventListener("load", function() {
outputFunction(this.response); // The callback
});
request.send(null);
};
// This is the callback
function outputFunction(a){
console.log(a);
};
requestFunction("data.txt");
It works. Now, inside the callback, I want to store the result in a variable, and use it outside the function. Something like:
// This is the callback
var storedObject = "Empty";
function outputFunction(a){
storedObject = a;
return storedObject;
};
But again, it doesn't works. ¿Is because the same reason as the previous code?