Elton Rodriguez Elton Rodriguez - 6 months ago 28
jQuery Question

Passing loaded json to multiple functions

So I have a few functions working to do multiple things however I need to pass a json object through most of them. Reasons behind why is the need to use multiple jsons.

I load my json using a function...

function LoadJSON(path) {
$.getJSON(path, function() { })
.done(function(results) { return results; })
.fail(function() { alert("Error loading content."); });
}


...from there I try to load it into a function...

function LoadScene(button) {
...
LoadButtons(LoadJSON('js/content.json'), id); // id is determined in code
}


...finally I try to access the data in the function I need it the most...

function LoadButtons(obj, id) {
alert(obj['data']);
}


... I have managed to load it directly without a load function or passing it from one function to another, however to make my code more efficient I need to properly separate things.

However, it's not working: I have managed to use the ajax call inside the LoadButtons function, however when I separate it into three separate functions, it won't work and the alert returns "undefined".

Any reason why this wouldn't work how I am implementing it?

Answer

Your LoadJSON won't ever return json because it's async - so LoadButtons(LoadJSON()) won't work.

You need to pass a callback function for the success, eg:

function LoadJSON(path, ondone) {
    $.getJSON(path, function() { })
        .done(function(results) { 
            if ($.isFunction(ondone)) ondone(results);
        })
        .fail(function() { alert("Error loading content."); });
}

function LoadDone(json)
{
    .. work with json
}

// call with:

LoadJSON('js/content.json', function(results) { LoadDone(results); })
//or
LoadJSON('js/content.json', LoadDone )

or use the promise directly:

function LoadJSON(path, ondone) {
    return $.getJSON(path, function() { })
        .fail(function() { alert("Error loading content."); });
}

LoadJSON('js/content.json')
    .done(function(results) {
        LoadDone(results)
    });

I wanted to add some detail regarding the return here:

function LoadJSON(path) {
    $.getJSON(path, function() { })
        .done(function(results) { return results; })
        .fail(function() { alert("Error loading content."); });
}

At first, I going to add that there's no return in LoadJSON so you'll always get null, but there "kind-of" is a return, it's in the .done. But this is not part of LoadJSON as it occurs later (as $.getJSON is async)

So what happens is:

  • LoadJSON starts
  • Sees $.getJSON and goes: ok - I'll start the ajax call given the details you've provided and returns immediately
  • LoadJSON exits (with no return statement, so returns null
  • The ajax call then completes and hits the .done which just returns the result back to the jquery ajax handler