I have the following code in javascript:
var max = 0; //<---- HERE
var request = new XMLHttpRequest();
request.open('GET', 'HERE_GOES_API_ADDRESS', true);
request.onload = function (max) { //<---- HERE
// Begin accessing JSON data here
var data = JSON.parse(this.response);
if (request.status >= 200 && request.status < 400) {
data.forEach(LoginLog => {
window['max'] = LoginLog.id; //<---- HERE
});
} else {
const errorMessage = document.createElement('marquee');
errorMessage.textContent = `Gah, it's not working!`;
app.appendChild(errorMessage);
}
}
request.send();
console.log(max); // <---- HERE Gives 0
The expected value of max
after the loop is 2
. However, I am always getting 0
.
why is the window
not working? isn't supposed to be used when updating a global variable?
P.S: I have to update the max
variable globally. console.log(max)
was written only for testing purposes.