The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Store JSON data in a variable Reply To: Store JSON data in a variable


AJAX is not (shouldn’t be) synchronous. This means that you cannot return the response to a var by assigning the the function call. (Even if you could, you’re not: your AJAX_JSON_req doesn’t return anything at all. You’re returning the ajax response inside the onReadyStateChange callback. This function is an event listener: it is triggered by the readystatechange event, not called form your code. Nothing can be done with its return value.)

Whatever you want to do with the ajax response needs to be done in your callback. e.g.,

AJAX_req.onreadystatechange = function() {
    if(AJAX_req.readyState == 4 && AJAX_req.status == 200){
        var response = JSON.parse(AJAX_req.responseText);
        console.log( response );
        //  ^---- in here  :)
// <---- not out here :(  ---->

You might be interested in the promise js library: promises make async functions a lot easier to think about, and promisejs also has built-in ajax functions.