2

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/

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.