Muthubaskar Krishnan
Muthubaskar Krishnan

Reputation: 21

How to Execute a function after two ajax requests are successful?

Function1()
{
    //Make Ajax Request
    $.ajax({
    url:url1,
    success:function abc(){
    }
})
...
}

Function2(){
//Make Ajax Request
$.ajax({
   url:url2,
   success:function cde(){
   }
})
...
}

Function3(){
//This function should execute after function 1 and 2 successfull.
...
}

Note: Function 3 should execute only after "sucess" function abc and "sucess" function cde completes execution.

Please do the needful

Upvotes: 2

Views: 291

Answers (3)

hutingung
hutingung

Reputation: 1800

You can use jQuery.when( deferreds ) - refer to http://api.jquery.com/jquery.when/

Code Snippet -

$(function() {
    $.when($.ajax("response1.json"), $.ajax("response2.json")).then(function(response1, response2) {
        console.log(response1, response2);
        $("#message").html("say hi to " + response1[0].name + " and " + response2[0].name);
    });

});

Demo at plunkr - http://plnkr.co/edit/abPYPUQ49G0MhrcED31Z?p=preview

Upvotes: 1

Amit Soni
Amit Soni

Reputation: 3316

var temp =0;

 Function1()
    {
        //Make Ajax Request
        $.ajax({
        url:url1,
        success:function abc(){
         temp++;
          if(temp==2)
             Function3() //call function here
        }
    })
    ...
    }

    Function2(){
    //Make Ajax Request
    $.ajax({
       url:url2,
       success:function cde(){
     temp++;
    if(temp==2)
      Function3() //call function here
       }
    })
    ...
    }

    Function3(){
    //This function should execute after function 1 and 2 successfull.
    ...
    }

Upvotes: 0

Rohan Kumar
Rohan Kumar

Reputation: 40639

You can try it like,

var flagFunc1=false;
var flagFunc2=false;

Function1()
{
    //Make Ajax Request
    $.ajax({
      url:url1,
       success:function abc(){  dummyFunction(1); }
    });
    ...
}    
Function2(){
   //Make Ajax Request
   $.ajax({
      url:url2,
      success:function cde(){ dummyFunction(2); }
   })
   ...
}
function dummyFunction(f){
   if(f==1){ // function 1 success
       flagFunc1=true;
   } else if(f==2) { // function 2 success
       flagFunc2=true;
   }
   if(flagFunc1==true && flagFunc2==true){
       Function3();//finally call function 3
   }
}
Function3(){
  //This function should execute after function 1 and 2 successfull.
  ...
}

Upvotes: 0

Related Questions