0

I have a Javascript file in which I need to read a json file using XMLHttpRequest and store the response into a global varibale so that I can use it elsewhere in my program, but I don't know why the response is not getting stored into the global variable. Can anyone please tell me why it's not getting stored and the way in which I can achieve it.

Here's the code I'm having

var xmlhttp = new XMLHttpRequest();
var url = './output.json';
var myArr;

xmlhttp.onreadystatechange = function () {
  if (this.readyState == 4 && this.status == 200) {
    let arr = JSON.parse(this.responseText);
    console.log(arr);
    myFunction(arr);
  }
};
xmlhttp.open('GET', url, true);
xmlhttp.send();

function myFunction(arr) {
  myArr = arr;
  console.log(myArr);
}

console.log(myArr);

The last console log says undefined.

I was expecting the last console log to show the json as an array.

Sunny Raj
  • 15
  • 6

2 Answers2

3

you can do this in simple way by directly assigning the api response to the global variable, like this:

    let myArr; // declare a global variable to store the response

    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'data.json', true);
    xhr.onload = function () {
      if (xhr.readyState === 4 && xhr.status === 200) {
        myArr= JSON.parse(xhr.responseText); // assign the response to the global variable
      }
    };
    xhr.send();

    // You can use the myArr variable anywhere in your program now
    console.log(myArr);
Rupali Yadav
  • 121
  • 4
  • Thanks for helping. It did worked out as intended. Alternatively I found one more solution to it as by changing the `xmlhttp.open('GET', url, true);` into `xmlhttp.open('GET', url, false);` this makes it synchronous. – Sunny Raj Apr 30 '23 at 07:52
  • That's great! Thanks for sharing the alternative – Rupali Yadav May 02 '23 at 15:16
1

XMLHttpRequest is an asynchronous operation.

So when you do a console.log outside of this operation, it's executed before the async part of the async part.

In order to work with myArr, you should stay in myFunction

Wandrille
  • 6,267
  • 3
  • 20
  • 43