Return $.get data in a function using jQuery

Viewed 90463

I'm trying to call a function that contains jQuery code. I want this function to return the results of the jQuery statement. It is not working, and I'm trying to figure out why.

function showGetResult (name) {
    var scriptURL = "somefile.php?name=" + name;
    return $.get(scriptURL, {}, function(data) { return data; });
}

alert (showGetResult("John"));

The alert displays "[object XMLHttpRequest]." However, if I run the jQuery statement by itself, outside of a function, it works fine -> $.get(scriptURL, {}, function(data) { alert(data); })

I'd like to be able to re-use this code by putting it inside of a function that returns the $.get data. What fundamental mistake am I making here?

6 Answers

An efficient way is to use jQuery's Deferred method, both sync/async requests to server and wait for deferred.resolve() and then return the deferred promise object. Looks a bit tedious, but a little study is sure helpful for large data. ( tvanfosson's function works well in this case, but when I was working on google analytics data, a large amount of information made me crazy and thus i need to find this solution)

     function showResults(name) { 
        var deferred = $.Deferred, requests = [];

        requests.push($.ajax({url:"/path/to/uri/?name=" + name, type: "GET", async: false}).done(function(d) { 
         //alert or process the results as you wish 
        }));
        $.when.apply(undefined, requests).then(function() { deferred.resolve(); }); 
        return deferred.promise();

    }

the returned promise object can also be used with $.when(showResults('benjamin')).done(function() { }); for post modifications (like chart/graph settings etc). totally reusable. You may also put this function in a loop of $.deferred requests like,

        function updateResults() { 
             var deferred = $.Deferred, requests = [];
             requests.push($.ajax(url:"/path/to/names/?nameArr=" + jsonArrOfNames, type: "GET", async: false}).done(function(res) {  requests.push(showResults(res[0]));}) );
             $.when.apply($, requests).then(function() { deferred.resolve(); }); 
             return deferred.promise();
            }
Related