0

I am attempting to manipulate data loaded from a local JSON file using this method (no jQuery) but seem not to be able to access the object on a global scope:

 var actual_JSON;

 function loadJSON(callback) {   
    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");
    xobj.open('GET', 'my_data.json', true);
    xobj.onreadystatechange = function () {
          if (xobj.readyState == 4 && xobj.status == "200") {
            callback(xobj.responseText);
          }
      };
    xobj.send(null);  
 }

The function then is called once the document is loaded, using an anonymous function as follows:

function loaded(e) {

    loadJSON( function(response) {
            actual_JSON = JSON.parse(response);
            console.log(actual_JSON); // Object {...}
        }
    );
    console.log(actual_JSON); // undefined
};

document.addEventListener("DOMContentLoaded", loaded, false);

Unfortunately I don't fully understand the concept of closures yet and whether/how it affects the scope of actual_JSON. It seems to be defined only inside the anonymous function passed to loadJSON() as callback for XMLHttpRequest(), although I declare it globally.

handle
  • 5,859
  • 3
  • 54
  • 82
  • 4
    it is in global scope, eventually, it's more a matter of timing than scope. you need to wait for callback to fire before the global is assigned. if you `console.log(actual_JSON )` from the console after running, you can see the global. – dandavis Jul 01 '15 at 07:42
  • You are right, using the console, I can see that actual_JSON is defined. – handle Jul 01 '15 at 07:46
  • While http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call is related, I disagree with it being a duplicate, as my question already uses a callback. The solution to my problem would be to run dependant code from inside the callback or to block interaction until the global object has been defined. – handle Jul 01 '15 at 07:55

1 Answers1

-1

Try to define actual_JSON in outer scope:

function loaded(e) {
    var actual_JSON;
    loadJSON( function(response) {
            actual_JSON = JSON.parse(response);
            console.log(actual_JSON); // Object {...}
        }
    );
    console.log(actual_JSON); // undefined
};

document.addEventListener("DOMContentLoaded", loaded, false);

This variable was defined in function(response) scope and it was not visible in loaded(e) scope.

suvroc
  • 3,058
  • 1
  • 15
  • 29