JavaScript function that returns the result of ajax call
Help is needed. I am writing a function that returns the result of an ajax call, but I didn’t get any results, I think this is a scope issue, but is there a way to do this? 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;
};
a source to share
Your problem is that the HTTP request you are making is asynchronous and your function Favorites
returns before the Ajax request is returned. You will need to modify your function to accept a callback that will be executed after the response:
function Favorites(callback) {
$.ajax({
type: "GET",
url: "/Services/Favorite.svc/Favorites",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function(msg) {
var links = (typeof msg.d == 'string') ? eval('(' + msg.d + ')') : msg.d;
callback(links);
}
});
};
Favorites( function(links) { alert(links); } );
Also, the convention is that only functions intended to be used as constructors must start with a capital letter, so your function will be better named Favorites
.
a source to share
Ajax is asynchronous, meaning that when it is executed return links
, the callback function success
may not even be 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);
a source to share