4

So i was trying to get json data and storing it in a variable. The problem is that everything inside the .onReadyStateChange block is like a blackhole, nothing gets out of there so I can't retrieve information. I can call functions from within that block and it will work, but anything i try to save to an outside entity will result in null, even if that variable is of the window scope.

var globalVar;

xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var foodsArray = JSON.parse(this.responseText);
        globalVar = JSON.stringify(foodsArray);
    }
}

console.log(globalVar);
//result will be null, so will foodsArray had I made it global

So my question is, is there any way to save that information outside of that block? Thanks.

goldensausage
  • 229
  • 1
  • 2
  • 11
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – mrlew Feb 08 '17 at 04:32

2 Answers2

1

Your console.log call is synchronous while the assignment to globalVar was done asynchronously, hence null was printed first even before the assignment resolved.

==edit==

You may choose to wrap the XMLHttpRequest object inside a Promise:

var prom = new Promise(function(resolve,reject) {
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            resolve(this.responseText);
        }
    }
});

prom.then(function(foodsArray) {
    console.log(foodsArray);
});
Rem Lampa
  • 451
  • 6
  • 6
1

First, you need to know the principle of the ajax. you konw, the ajax is an async function, so when you haven't gotten the return value, 'console.log(globalVar)' has been executed. So you should write in the way:

var globalVar;

xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var foodsArray = JSON.parse(this.responseText);
        globalVar = JSON.stringify(foodsArray);
        console.log(globalVar); // you can get the result
    }
}
Mohammad Sadiqur Rahman
  • 5,379
  • 7
  • 31
  • 45
Luke Lee
  • 36
  • 1
  • 1
    I see, but my objective though is to get the json data, then save it in some data structure in the window scope so that I can access that data any time later on in my web application so that I don't need to make a rest request every time i need the data – goldensausage Feb 09 '17 at 14:39