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,
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.
.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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With