Reputation: 506
I am calling a function which is getting a value using ajax how to return this value to a calling function:
My function with ajax call is:
function getStatusOfAdv(advID){
$.ajax({
url:baseURL+"/admin/advertisers/get.adv.status.php",
data:"param="+escape(advID),
dataType:"html",
cache:"false",
success:function(result){
return result;
}
});
}
I have to return this result value to calling function which is:
function setAdvDetail(advID){
var status = getStatusOfAdv(advID);
alert(status);
}
Upvotes: 2
Views: 305
Reputation:
you can make async to false..
try
function getStatusOfAdv(advID){
var Result;
$.ajax({
url:baseURL+"/admin/advertisers/get.adv.status.php",
data:"param="+escape(advID),
dataType:"html",
cache:"false",
async:"false"
success:function(result){
Result=result;
}
});
return Result;
}
But making async to false is not a good practice.
Upvotes: 0
Reputation: 707546
$.ajax()
calls are asynchronous so getStatusOfAdv()
returns before the ajax call has completed. As such, you will have to restructure your code so that all code that uses the result of the asynchronous function is either in the ajax success handler or is called from that handler.
You can't make a synchronous function like getStatusOfAdv()
, use an asychronous call inside it and then return the value when getStatusOfAdv()
returns. It cannot be done because getStatusOfAdv()
returns long before the asynchronous ajax call has completed, thus the return value is not yet known when it returns.
The typical design pattern in javascript is to do the work that needs the answer in a callback function that is called when the async operation is done and the data is available:
function getStatusOfAdv(advID, fn){
$.ajax({
url:baseURL+"/admin/advertisers/get.adv.status.php",
data:"param="+escape(advID),
dataType:"html",
cache:"false",
success:function(result){
fn(result);
}
});
}
function setAdvDetail(advID){
getStatusOfAdv(advID, function(status) {
alert(status);
// any other code that uses the status goes here
});
// the status is NOT known here because the asynch function has
// not yet completed
}
Upvotes: 1
Reputation: 23801
Try this
function getStatusOfAdv(advID){
$.ajax({
url:baseURL+"/admin/advertisers/get.adv.status.php",
data:"param="+escape(advID),
dataType:"html",
cache:"false",
success:function(result){
alert(result);
}
});
}
After all this is what u are doing after the ajax function Call
Upvotes: 0
Reputation: 148150
$.ajax
is async
call and the getStatusOfAdv function will return before success you can call a function from success and pass result to it.
function getStatusOfAdv(advID){
$.ajax({
url:baseURL+"/admin/advertisers/get.adv.status.php",
data:"param="+escape(advID),
dataType:"html",
cache:"false",
success:function(result){
callYourFunction(result);
}
});
}
function callYourFunction(result)
{
}
Upvotes: 2