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.