1

I am trying to receive data from an API that contains JSON data that includes rundate and a start number. I want to store the start number as a global variable (test) to use in other functions.

var test=0;

var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var myObj = JSON.parse(this.responseText);
           // retrieve data from server
            document.getElementById("rundate").innerHTML = myObj[0].rundate;
            document.getElementById("startnumber").innerHTML = myObj[0].startnumber;
            var test = parseInt(myObj[0].startnumber); 
        }
      };  

    // send data to server
    xhttp.open("GET", "https://digitalordersdata.cfappstpanp.ebiz.verizon.com/getdigitalOrdersData", true);
    xhttp.send();

alert(test);

So as you can see from above I am able to store and display the number I received by using the IDs but I am unable to redefine the variable test and use the number in another function. The alert still has the original value of 0.

Thanks in advance for the help.

Ryan Romo
  • 11
  • 1
  • 2
    Remove `var` from `var test = parseInt(myObj[0].startnumber);`. You're creating a new variable in the function's scope. Also, you're running `alert` immediately, whereas the code in `onreadystatechange` runs at some point in the future. – Frank Modica Nov 12 '18 at 18:50
  • any code you want to use the variable in must be triggered from your onreadystatechange. This is because ajax calls are asynchronous. Until that function runs, your value doesn't exist. But JS will not wait for it to happen - it carries on executing all your other code in the meantime. If you want you can put the value into a global (you must omit the `var` - otherwise it re-declares it with a scope local to the function), but you can't _use_ the value in the global until after the AJAX call has completed. – ADyson Nov 12 '18 at 18:55

0 Answers0