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.
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);