jQuery getJSON - Return value to the caller function

Alon Gubkin picture Alon Gubkin · Aug 4, 2009 · Viewed 14.6k times · Source
    String.prototype.getLanguage = function() {
        $.getJSON('http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q=' + this + '&callback=?',
            function(json) {
               return json.responseData.language;
            });
    };

How can I return the value to the caller value? Thanks.

EDIT: I've tried this:

    String.prototype.getLanguage = function() {
        var returnValue = null;

        $.getJSON('http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q=' + this + '&callback=?',
            function(json) {
               returnValue = json.responseData.language;
            });

        return returnValue;
    };

But it's not working either. It returns null.

Answer

coderjoe picture coderjoe · Aug 4, 2009

I'm assuming you want to use a synchronous event so that your String.prototype.getLanguage() function will just return the JSON. Unfortunately you can't do that with jQuery from a remote API.

As far as I know jQuery does not support synchronous XMLHttpRequest objects, and even if it did, you'd need to have a proxy on your server to make the sync request while avoiding the restrictions of the same-origin policy.

You can, however, do what you want using jQuery's support for JSONP. If we just write String.prototype.getLanguage() to support a callback:

String.prototype.getLanguage = function( callback ) {
    var thisObj = this;
    var url = 'http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q=' + this + '&callback=?';

    $.getJSON( url,function(json) {
                callback.call(thisObj,json.responseData.language);
    });
}

Then we can use the function as such:

'this is my string'.getLanguage( function( language ) {
    //Do what you want with the result here, but keep in mind that it is async!
    alert(this);
    alert(language);
});