Having an issue with storing JSON data retrieved using XMLHttpRequest into a global variable within my JavaScript file. Despite setting up the code to store the response in a global variable, it doesn't seem to be working as expected. Would appreciate any insights on why this might be happening and how I can achieve successful storage.
Below is the code snippet:
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 final console log output indicates 'undefined' instead of displaying the expected JSON array.
Hoping for a solution where the last console log accurately displays the JSON data as an array.