Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery getJSON - Return value to the caller function

    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.

like image 905
Alon Gubkin Avatar asked Aug 04 '09 19:08

Alon Gubkin


2 Answers

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);
});
like image 116
coderjoe Avatar answered Oct 06 '22 16:10

coderjoe


var test = function(fun)
{

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

};

test(retCall);

var retCall = function(xjson){
   alert(xjson);
};
like image 1
andres descalzo Avatar answered Oct 06 '22 17:10

andres descalzo