Jeff Walden
Jeff Walden

Reputation: 321

Using .each() with AJAX, wait until loop is done

For each checkbox checked, I need to execute an AJAX request which is being handled inside of an each loop. When all AJAX requests are complete, I need to execute a follow-up function.

The number of checkboxes is always variable and I only need to run the AJAX if the box is checked.

The HTML:

<input type="checkbox" class="checkbox" val="1" />
<input type="checkbox" class="checkbox" val="2" />
<input type="checkbox" class="checkbox" val="3" />
<input type="checkbox" class="checkbox" val="4" />
<input type="checkbox" class="checkbox" val="5" />

<button id="btn1">Click Me</button>

jQuery (v2.1.4)

$(document).on('click', '#btn1', function() {
    $('.checkbox').each(function() {
         // We only want the checked boxes
   if ($(this).is(':checked')) {
             // Do the thing
             $.get('test.html', function(data) {
                 console.log('Response received: ' + $(this).val());
             });
         }
    });
    console.log('All responses received');
});

What can I use to delay the final callback ("All responses received", in this example) until ALL of the AJAX requests are complete?

JSFiddle: https://jsfiddle.net/sjkhh43x/

Upvotes: 2

Views: 478

Answers (1)

charlietfl
charlietfl

Reputation: 171669

Create an array of promises returned by each $.get and use $.when to run code when all have resolved

$(document).on('click', '#btn1', function() {
  var promises = $('.checkbox:checked').map(function() {
    var $input = $(this)
    return $.get('data.html', function(data) {
      console.log('Response received: ' + $input.val());
    });
  }).get();

  $.when.apply(null, promises).done(function() {
    console.log('all done')
  })

});

DEMO

Upvotes: 1

Related Questions