Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap a jquery function and return a value

You can I wrap this code so that when a call a function returns the variable contianing the json object?

Example:

   function GetNewSomething() {
        var newtb = 0;
        $.get("/something/new",
                function (data) {
                    newtb = data;
                }
                );
        return newtb; // as of now this always returns undefined...
    }

Tried this way, but only return undefined..

Thanks in advance guys!

regards,

like image 771
byte_slave Avatar asked Apr 21 '26 10:04

byte_slave


2 Answers

You can't. Ajax calls are asynchronous. You have to pass a callback to your function:

function GetNewSomething(cb) {
    $.get("/something/new", cb);
}

and call it with:

GetNewSomething(function(data) {
    // do something with data
});

I wrote something about it.

Oh and if the response is a JSON string, you might want to use .getJSON which also decodes the response into a JavaScript object.

like image 108
Felix Kling Avatar answered Apr 23 '26 22:04

Felix Kling


.get() is a wrapper to $.ajax(). All AJAX request run asyncronously if not explicitly configured otherwise. That in turn means, that your return newtb; statement will occur before $.get() has finished.

A good way to workaround this issue is to invoke another callback on your own. This could look like:

function GetNewSomething(callback) {
    $.get("/something/new",
            function (data) {
                if( typeof callback === 'function' )
                    callback.apply(this, [data]);
            }
            );
}

And then call it like

GetNewSomething(function(data) {
     // do something with data
});
like image 24
jAndy Avatar answered Apr 23 '26 22:04

jAndy