1

I'm unable to correctly return (or maybe "capture" is a better term) a JSON object from within a function that runs on page load. I'd like to capture that object so that I can subsequently POST it to another page by user action.

I'm running this on Windows 10, Firefox latest.

var configJson;
$(document).ready(function () { // Wait till page is loaded
    configJson = getConfig();
    console.log("Outside: " + JSON.stringify(configJson)); // DEBUG
});

function getConfig() {
    var jqxhr = $.getJSON("/config/", function () {
        //console.log("Success."); // DEBUG
    })
        .done(function (data) {
            console.log("Inside: " + JSON.stringify(data)); // DEBUG
            return data;
        })
        .fail(function () {
            console.log("Fail."); // DEBUG
            return JSON.parse("{}");
        })
}

From the console, "Outside" is what is returned, "Inside" is what's seen in the function:

Inside: {"name":"fred"}
Outside: undefined
1
  • 1
    Yes, it's because your ajax call $.getJSON is async. So the console.log("Outside") is executed before the end of the $.getJSON call. You can use a callback in the function getConfig() and call a console log with the result of the callback. You can take a look in the doc for the deffered object and see some examples. api.jquery.com/jquery.when Commented Sep 16, 2019 at 16:56

1 Answer 1

2

You cannot return data from an asynchronous function, so you will need to use a callback. Like so:

$(document).ready(function () {
    getConfig(function(configJson) {
        console.log("Outside: " + JSON.stringify(configJson));
        // do something with configJson here.
    });
});

function getConfig(callback) {
    var jqxhr = $.getJSON("/config/")
        .done(function (data) {
            console.log("Inside: " + JSON.stringify(data));
            callback(data);
        })
        .fail(function () {
            console.log("Failed!");
            callback({});
        });
}

If you need a global variable containing the config, you could do something like this:

var globalConfig = {};
$(document).ready(function () {
    getConfig(function(configJson) {
        globalConfig = configJson;
    });
});
// ...
Sign up to request clarification or add additional context in comments.

1 Comment

And I even ready that about async and completely spaced it! Thank you for your assistance.

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.