byte_slave
byte_slave

Reputation: 1378

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,

Upvotes: 3

Views: 880

Answers (4)

Felix Kling
Felix Kling

Reputation: 816282

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.

Upvotes: 6

amurra
amurra

Reputation: 15401

You could change to make the $.get a $.ajax and make it syncronous since $.get is just a wrapper for a $.ajax:

function GetNewSomething() {
        var newtb = 0;
        $.ajax({url:"/something/new",
                type:"GET",
                async:false,
                success: function (data) {
                    newtb = data;
                }
          });
        return newtb; 
    }

Upvotes: 0

jAndy
jAndy

Reputation: 235962

.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
});

Upvotes: 3

Jamiec
Jamiec

Reputation: 136074

The $.get is asyncronous, which is the reason you pass it a function to call when the get request returns.

Upvotes: 0

Related Questions