0

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.

3
  • XHR is asynchronous. Commented Oct 30, 2016 at 18:11
  • What the mister above me said. Your options are to pass success/error callbacks to loadJSON or wrap the native XHR in native/library Promise. Commented Oct 30, 2016 at 18:13
  • i tried to add the callbacks but i still cant seem to figure out how to return the value. Commented Oct 30, 2016 at 18:19

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank-you for clearing that up. i guess ill just use php for hopefully synchronous execution.
.. meaning you will generate the JavaScript code by PHP when the JSON object is available?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.