0

I need to make two async (Second call needs to be made only when some condition is true) calls and when both the calls returns data, I need to make another call. For this I decided to use jquery $when.

Before I make second Ajax call, I need to check some condition. And if its true, then I need to make second ajax call otherwise, there is no need to make second ajax call.

Here is Pseudo-code

 $.when($.get(url, function (result, status, xhr) {
        myresult = result;
    })),
    (
        //If XYZ === 10
          //Make second Ajax call only if condition is true

    ).then(function (r1, r2) {
        //DO something

     });

How can I achieve this ?? With Jquery or any other library ??

SharpCoder
  • 18,279
  • 43
  • 153
  • 249
  • 2
    Your description seems contradictory. First, "I need to make two async calls and when both the calls returns data, I need to make another call" and then you say that the second call is only made based on the result of the first. Can you clarify what you're asking? Btw, the answer is yes - you can achieve this using jQuery. – Colin Brock Nov 14 '14 at 05:20
  • @Colin: I need to make second Ajax call only when some condition is true. If I am making second call, then only when I get data from both the call, I should make the final call. – SharpCoder Nov 14 '14 at 05:28

3 Answers3

0

Execute a function after two ajax requests are successful.

$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).done(function( a1, a2 ) {

  //if both the calls are sucess then only you can reach here.
  //  inside this you can make your third ajax call.

  }
});
KanhuP2012
  • 407
  • 3
  • 9
  • 2
    In this case, I need not make use of `$when`. I can make Ajax call and on the success of it, i can make second ajax call if required (based on some condition). – SharpCoder Nov 14 '14 at 05:35
0
var first = $.ajax(...);
var second = (condition) ? $.ajax(...) : $.Deferred().resolve(); // ajax only on condition

$.when(first, second).then(function(res1, res2){
    // work with res1 and res2, res2 is undefined if no call was made
});
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
0

You can use ternary operator for second ajax call. pass null value if condition is false as second parameter to $.when.

Here is Pseudo-code

$.when(
    //first ajax call ,
    (XYZ===10) ? //second ajax call 
               : null
       ).then(function (r1, r2) {
        //DO something

     });

Hope it helps.

Demo:- jsfiddle.net/NF2jz/5721 (try for a=0 and a=1)

yajiv
  • 2,901
  • 2
  • 15
  • 25
  • @VladislavDimitrov see this demo. http://jsfiddle.net/NF2jz/5721/ change value of a to 1 and it will update text according to second request. – yajiv Dec 21 '17 at 14:54