Purushottam zende Purushottam zende - 25 days ago 9
Javascript Question

Javascript When and Done Function use

I am trying to call two different functions in third function but one after the other.One function has ajax call, whose values are used in other function. it is step by step process. I don't want to use one into the other.

function f1()
{
// ajax call
return r1
}

function f2(r2)
{
// do some of the work based on r2
}

function f3()
{
$.when(f1()).done(function(data){
f2(data)

});
}


I also tried with $.when().then(); but still of no use.

Thanks, in advance.

UPDATE :- Below is the answer for my Question based on solution provide by @dreamweiver.

var json_data = '';
function f1()
{

$.ajax({
url: "test.php",
method: "POST",
async : false,
data: { },
success:function(data){
json_data = eval(data);
}

});


}

function f2(t)
{

console.log("values is "+t);
}

function f3()
{
$.when(f1()).done(function(){
f2(json_data);
});
}


Thanks everyone for your feedbacks.

Answer

Try this way, i have tested locally and it works perfectly

function deferredCalls () {
   var jsonData = '';
   var f1 = function ()
   {
       // ajax call 
       $.ajax({
         url: "test.html",
         method: "POST",
         data: { id : menuId }
       }).done(function(data) {
          jsonData = data; //set the data
       });
   }

   var f2 = function (data)
   {
     // do some of the work based on data
     if(!!data){
       //process the data
     }
   }
   $.when(f1).done(function(){
        f2(jsonData);
   });
 }

f1 function is called first which would inturn make a ajax request and return data on success, which is set to a function scope variable jsonData. Once this process is completed, f2 would be called which will start using jsonData, which is nothing but the data received from f1 function call.

Happy Coding :)

Comments