Search code examples
javascriptjsonxmlhttprequestreturn

Return JSON from XMLHttpRequest Function


Hello I've been trying to wrap my head around returning data from a XMLHttpRequest Function. I've tried many different ways but the only thing i can get when i try to output the data to a console from out-side the function i always get 'undefined'. it only works if i do it from inside the function itself.

<script>
var object;

function loadJSON(path, success, error) {
    var xhr = new XMLHttpRequest();
    var obj1;
    xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {
                if (success)
                success(JSON.parse(xhr.responseText));
                //console.log(data); works here!
            } else {
                if (error)
                error(xhr);
            }
        }
    };
    xhr.open("GET", path, true);
    xhr.send();
}


object = loadJSON('jconfig.json',
function (data) { console.log(data); return($data);/*works here! but does not return!*/ },
function (xhr) { console.error(xhr); }
);

console.log(object);//does not work here
</script>

I know this is a very simple problem but I've been stuck with this problem for over an hour now and the answers given on other similar questions cant seem to get me over this obstacle. Any help is highly appreciated!

EDIT: I updated the code with some suggestions but i still cant get ti to work. Any suggestions to get the code above to finally return something i can use outside of the functions.


Solution

  • The line console.log(object) is executed just after the laodJSON() function is called and the JSON object isn't loaded till then.

    This is related to callbacks and async functions. Your loadJSON() can only actually load the JSON when it get's response from the server.

    Instead, if you want to call the JSON object outside the loadJSON() function, you need to use a callback function. Something like this:

    <script>
    var object;
    
    function loadJSON(path, callback) {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState === XMLHttpRequest.DONE) {
                if (xhr.status === 200) {
                    // Here the callback gets implemented
                    object = JSON.parse(xhr.responseText);
                    callback();
                } else {
    
                }
            }
        };
    
        xhr.open("GET", path, true);
        xhr.send();
        return xhr.onreadystatechange();
    }
    
    loadJSON('jconfig.json', function printJSONObject(){
              console.log(object);
        });
    
    // this will not work unless you get the response
    console.log(object);
    
    </script>
    

    Update: "Returning" a value from an async function by the use of callbacks is pointless, since the next line of code will be executed immediately without waiting for the response.

    Instead, if you want to use the object outside of the function sending an XHR request, implement everything inside your callback function.