0

When I use console.log(actual_JSON) I actually see my array of objects but if I return it from within a function like return actual_JSON I have an undefined array. What is happening? This is my js:

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

    xobj.send(null);
}

function init() {
    alert("hi");
    loadJSON(function (response) {
        var actual_JSON = JSON.parse(response);
        console.log(actual_JSON);
    })
}

My JSON file looks like:

[
  {
    "username": "lovelyday", 
    "email": "lovelyday@gmail.com"
  }, 
  {
    "username": "what", 
    "email": "whoknows@nothing.com"
  }
]
Shanoor
  • 13,344
  • 2
  • 29
  • 40
Lucky Lam
  • 125
  • 2
  • 14
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Leon Adler Dec 06 '15 at 07:53
  • You cannot return to the outer function, and `loadJSON` is asynchronous. You can pass a callback to `init` though. – elclanrs Dec 06 '15 at 07:53
  • Do you mean JSON.stringify(response)? because response.text is json, and you want an array – vdj4y Dec 06 '15 at 07:58

0 Answers0