$.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
}