Question

I have a function where I'm making a call to a MVC controller that returns a JSON blob, with the contents of some back-end action. This JSON blob is being used to populate a table that is presented to the end-user.

My function currently looks something like this:

function getJsonFromController(path) {
    var blob = null;

    $.getJSON(path, function (data) {
        blob = data;
        console.log('inside getjson : ' + blob);
    });

    console.log('outside getjson : ' + blob);
    return blob;
}

...And a calling action that looks like this:

$('#action-button').click(new function () {
    blob = getJsonFromController('A/B?pageId=1');

    console.log('in click event: ' + blob);
    $.tmpl($template, blob).appendTo($('#table-body'));
});

When I run the webpage/action that calls this, I get the following results, in the given order:

outside getjson: null
in click event: null
inside getjson: [object Object] 

I've attempted some other configurations (.complete of .getJSON(), directly returning a value from $.getJSON()) to attempt to echo the 'data' from the callback out to the enclosing scope's blob variable, but so far, the blob only appears to have value within the getJSON callback.

That being said, I'm also aware that JavaScript is a lexically scoped language, so it could be a matter of all the anonymous function chains being executed.

The question: I can see that my blob is appearing correctly inside $.getJSON. Now, how do I get my blob out?

Was it helpful?

Solution

AJAX requests are asynchronous. You may do it synchronous (note that it will freeze your web page until request is done), but suppose better will be to do something like below:

function getJsonFromController(path) {
    var blob = null;

    $.getJSON(path, function (data) {
        blob = data;
        console.log('inside getjson : ' + blob);
        $.tmpl($template, blob).appendTo($('#table-body'));
    });
}

And click:

$('#action-button').click(new function () {
    blob = getJsonFromController('A/B?pageId=1');
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top