Search code examples
jquerygetjsonjquery-callback

jQuery - Best practice when returning content from getJson request to caller function


What is the best practice when returning content from the result of a $.getJson request to a caller function? I have a function called $.fn.getSomeData which has a $.getJson call inside it (this function is in a JS file which JSP's wanting to use my webservice must import).

Then inside the calling JSP a function will call my $.fn.getSomeData function.

Because my $.getjson request is asynchronous I have to wait for the callback function to execute before i can think about processing the JSON. What is the best way to handle passind the resulting data back to the function in the calling JSP.

Other options i have read including passing a Div into the $.fn.getSomeData method and then in the $.getJson callback function I would do processing of the json and append to the Div as I want it to appears.

A second option was to pass a function into $.fn.getSomeData. This function can then be called in the $.getjson callback function.

Can someone recommend a best practice? I would prefer not to use the option of passing the Div into my $.fn.getSomeData function as i want to reduce coupling in my external JS file.

Also is there a way to add a callback function to the call I make from the JSP to $.fn.getSomeData that would somehow trigger once the $.getjson callback has executed?

Looking forward to hearing your suggestions.


Solution

  • The 2nd version is what you want.

    Pass in the function that you want to be executed when the getJson request completes.

    $.fn.getSomeData = function(callback) {
        $.getJSON('url', data, callback);
    }
    
    $('div').getSomeData(function() { 
        // do something
    });
    

    To process the data first and then call the function do this:

    $.fn.getSomeData = function(callback) {
        $.getJSON('url', data, function(result) {
            // do something with data
            callback(result);
        });
    }