0

I'm trying to access data from a JSON file but the result of the console is undefined.

The GET response is good, the function works but I don't know how to access the response.

function AJAX_JSON_Req(url) {
    var AJAX_req = new XMLHttpRequest();
    AJAX_req.open("GET", url, true);
    AJAX_req.setRequestHeader("Content-type", "application/json");

    AJAX_req.onreadystatechange = function() {
        if(AJAX_req.readyState == 4 && AJAX_req.status == 200){
            return JSON.parse(AJAX_req.responseText);
        }
    };

    AJAX_req.send();
}

var q = AJAX_JSON_Req('questions.json');

console.log(q); //undefined

http://codepen.io/gsg/pen/LEEeMg

Biffen
  • 6,249
  • 6
  • 28
  • 36
GSG
  • 53
  • 8

2 Answers2

1

Remember that this is an asynchronous function. Try using a callback instead and see if you have more success.

function AJAX_JSON_Req(url, callback) {
    var AJAX_req = new XMLHttpRequest();
    AJAX_req.open("GET", url, true);
    AJAX_req.setRequestHeader("Content-type", "application/json");

    AJAX_req.onreadystatechange = function() {
        if(AJAX_req.readyState == 4 && AJAX_req.status == 200){
            callback(JSON.parse(AJAX_req.responseText));
        }
    };

    AJAX_req.send();
}

AJAX_JSON_Req('questions.json', function (q) {
  console.log(q);
});
Andy
  • 61,948
  • 13
  • 68
  • 95
0

AJAX stands for Asyncronous JavaScript and XML.

This means that when your function ends you don't have the data yet.

onreadystatechange is an event listener. It's a non-standard form of:

AJAX_req.addEventListener("readystatechange", function () {
    // state changed
});

A simple solution would be to pass in a callback, like:

AJAX_JSON_Req("questions.json", function (reply) {
    console.log(reply);
});

And have:

AJAX_req.addEventListener("readystatechange", function () {
    // check state == 4
    callback(JSON.parse(AJAX_req.responseText));
});

A common approach of dealing with asynchronousness is the use of Promises. This avoids callback hell.

So you'll get something like:

AJAX_JSON_Req("questions.json").done(function (reply) {
    console.log(reply);
});

Promises are not natively available (yet) but you can write your own implementation or use one of the popular frameworks.

Now AJAX_JSON_Req("questions.json") returns something: a Promise. You don't have the value yet, but you have the promise that eventually you will get it.

Halcyon
  • 57,230
  • 10
  • 89
  • 128