
Working with AJAX stuff is really cool. Recently when I was creating a related post stuff that loads stuff asynchronously, I was able to load stuff but the value was not returning. On searching I found that async requests do not return value with an ordinary way, you need callback.
There are two ways to return value in async function. First is to do a callback function once the function is completed, second is to use jQuery's deferred method. jQuery's deferred method uses when and done, means under "when" add your async request and under "done" you can access the variables of completed async request.
Lets start with callback function. Lets create function with a loop.
function foo(callback){
};
I have only one argument, however you can pass several but this argument has a reason. Lets move on:
function foo(callback){
$.ajax({
type:'GET',
url:'http://graph.facebook.com/?id=http://bloggerever.com',
contentType:'aplication/json',
success:function(e){
callback(e.shares);
}
});
}
The above function returns the number of shares. The return value is under a function, well function name could be any name but here it is callback. When I will run the function foo then this will return an other function. We can access the return value of shares through it.
foo(function(returnVal){
console.log(returnVal); // Logs number of shares
});
If we would have returned the value directly instead of callback, the returned value will be undefined. In case you change async to false then without any callback you can return the value normally.Lets move on to the second way which is deferred method.
$.when(
// Ajax Request
).done(function(e){
// Do something with returned ajax content
});
The above code can be processed with deferred method with this code.
$.when(
$.ajax({
type:'GET',
url:'http://graph.facebook.com/?id=http://bloggerever.com',
contentType:'aplication/json'
})
).done(function(r){
console.log(r.shares);
});
You can't return a value after async request but .done() let you do the function with the return value when request is completed. This method helps a lot when multiple ajax requests are being processed and a single callback is required. You can learn more about it here.
Post A Comment:
0 comments: