1

I am trying to read from a local myjson.json file and print its content to my index.html. I am using the following JavaScript code:

function getJSON() {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', '/myfolder/myjson.json', false);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == XMLHttpRequest.DONE) {
        var response = xhr.responseText;
        console.log("response: " + response); //Correctly prints JSON content to console
        return response; //response is undefined when called from html
        }
    }
    xhr.send(null);
}

I am calling the function getJSON() like so:

document.getElementById("contentOfJSON").innerHTML += "JSON: "+getJSON();

This prints out the content of myjson.json correctly to console.log, but my HTML-Element "contentOfJSON" contains only "JSON: undefined". Why am I getting an undefined response eventhough the console.log is working?

G. Werner
  • 199
  • 2
  • 14

1 Answers1

1

You're returning the string to the call on onreadystatechange.

Your function getJSON returns nothing.

From what I've seen, sync is suppose to be depreciated so just make it async by passing a success function into getJSON and then calling it by passing the result string into callback.

function getJSON(mycallback) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', '/myfolder/myjson.json', false);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == XMLHttpRequest.DONE) {
        var response = xhr.responseText;
        console.log("response: " + response); //Correctly prints JSON content to console

        // call it here
        mycallback(response);
        }
    }
    xhr.send(null);
}


getJSON(function(result)
{
    document.getElementById("contentOfJSON").innerHTML += "JSON: " + result;
});
John
  • 5,942
  • 3
  • 42
  • 79