Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally add to jQuery .when

When my page loads, I make one AJAX call, and then another conditionally upon what is on the page. I want to call a function at the end of both; how do I do it?

var dfd = $.when( $.ajax(...) );

if( $("type").val() == "something" ) {
  dfd.when( $.ajax(...) );
}

dfd.then(function() { 
   // final code
});

I can't find much about adding to $.when "conditionally" or "later" as those search terms are too close to the original purpose of the promise itself, so I just get the standard usage of $.when(a, b).then(c)

Thanks

like image 677
Sean Avatar asked Mar 20 '26 22:03

Sean


1 Answers

Your code should look more like this:

var dfd = $.ajax(...);
var dfd2 = $.ajax(...);

var deferreds = [];

if($("type").val() == "something")
    deferreds.push(dfd)

if($("other").val() == "somethingElse")
    deferreds.push(dfd2)

$.when.apply( $, deferreds )
  .then( callback, failureCallback );

ref: https://api.jquery.com/jQuery.when/

like image 107
Mister Epic Avatar answered Mar 23 '26 13:03

Mister Epic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!