Help needed. Im writing a function that returns result of ajax call but i did not get any results, i guess it's a scope issue, but is there any way to do it? Here is my code:
function Favorites() {
var links;
$.ajax({
type: "GET",
url: "/Services/Favorite.svc/Favorites",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function(msg) {
links = (typeof msg.d) == 'string' ? eval('(' + msg.d + ')') : msg.d;
}
});
return links;
};
Ajax is asynchronous, i.e. when return links is executed, the callback function in success might not even have been called.
Extend your function to accept a callback:
function Favorites(callback) {
var links;
$.ajax({
type: "GET",
url: "/Services/Favorite.svc/Favorites",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: callback
});
};
and call it with:
var callback = function(msg) {
links = (typeof msg.d) == 'string' ? eval('(' + msg.d + ')') : msg.d;
// do other stuff with links here
}
Favorites(callback);
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