1

I want to store the length of a Json array as a global variable to make my code more modular. I am trying to set the global variable inside the .onload function but it won't allow this. I have tried with a globalTest variable.

var objectLength = 0;
var globalTest = 0;

$(document).ready(function() {
    establishConnection();
});


function establishConnection() {
    xttp = new XMLHttpRequest();
    xttp.open("GET", "http://exampleServerPath", true);
    xttp.send("null");

    xttp.onload = function() {
        var Json = JSON.parse(this.response);
        objectLength = Json.length;
        globalTest = 2; // this doesn't work         
    };

    globalTest = 4; //this works
}

I am fairly new to JS any help is appreciated!

Mephistofee
  • 73
  • 1
  • 10
  • It *does* work, just not when you think it does. – Dave Newton Apr 06 '17 at 17:38
  • I have this question too, and the proposed duplicate does not have a solution to my scenario, and the point of the question is different...I'd say it's not a duplicate and needs a clear (specific) answer. – Aaron Bramson Jun 29 '18 at 05:52

1 Answers1

0

I think the issue lies with the xttp.onload part. Change that to xttp.onreadystatechange and then check the readystate.

Check out this example.

EDIT: Your code works as expected, but maybe you think globalTest is not being updated.

If you were to call establishConnection() and then immediately try to access globalTest it will still be 0 because the AJAX request has not completed yet.

If you did

establishConnection();
setTimeout(function() {
    alert(globalTest);
}, 2000);

Then you should see the value you expect (assuming your ajax request completes in less than 2 seconds.

HoofHarted
  • 176
  • 2
  • 5