Skip to content Skip to sidebar Skip to footer

How To Get Value From A Javascript Function Which Is Using Ajax

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){ $.aj

Solution 1:

$.ajax is async call and the getStatusOfAdv function will return before success you can call a function from success and pass result to it.

functiongetStatusOfAdv(advID){
   $.ajax({
      url:baseURL+"/admin/advertisers/get.adv.status.php",
      data:"param="+escape(advID),
      dataType:"html",
      cache:"false",
      success:function(result){
         callYourFunction(result);
      }
   });
}

functioncallYourFunction(result)
{

}

Solution 2:

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

functiongetStatusOfAdv(advID, fn){
   $.ajax({
      url:baseURL+"/admin/advertisers/get.adv.status.php",
      data:"param="+escape(advID),
      dataType:"html",
      cache:"false",
      success:function(result){
         fn(result);
      }
   });
}

functionsetAdvDetail(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
}

Solution 3:

Try this

functiongetStatusOfAdv(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

Post a Comment for "How To Get Value From A Javascript Function Which Is Using Ajax"