0

I'm really new to the matter so please bear with me on this one. I have to parse a json file that is structured this way:

    {"elements": [{
            "id": 1,
            "name": "my name",
            "description": "my description",
        }, 
        {
            "id": 2,
            "name": "my name 2",
            "description": "my description 2",
        },

and I'm doing this as follows, using xmlhttprequest and JSON.parse:

//      asynchronous call to open the cards json
        request.open("GET", "../json/stuff.json", true);

//      send request to web server
        request.send();

//      onreadystatechange fires when the request state changes
        request.onreadystatechange = function() {
//            if the readystate is 4 the response from web server is ready
//            if the request status is 200 the status is ok
              if (request.readyState === 4 && request.status === 200 ) {
                 stuff = JSON.parse(request.responseText);
                 console.log("here");
              }
        }

        console.log(stuff[0]);

the "request" variable, just like "stuff", is defined at global scope as follows:

var request = new XMLHttpRequest();

The problem I get is that "stuff" is undefined, and I can't figure out why.

Andrew
  • 358
  • 10
  • 23

1 Answers1

1

You are using sync code in async code. The request.onreadystatechange is callback, therefore the console.log is called before the request.onreadystatechange. So:

request.onreadystatechange = function() {
        if the request status is 200 the status is ok
          if (request.readyState === 4 && request.status === 200 ) {
             stuff = JSON.parse(request.responseText);
             console.log(stuff[0]);
          }
    }
Vinz243
  • 9,654
  • 10
  • 42
  • 86