0

I'm trying to call an ajax function for every selected checkbox on a page. Once all of those ajax calls have completed, I want to do something else. In the example below, the 'all calls completed' text is written to the console before any of the 'single call completed' text. How can I make this wait until all ajax calls are finished? Thanks!!

function ajax_function() {
  return $.ajax({
    url: "submit.php",
    type: "POST",
    dataType: "json",
    data: form_data,
    cache: false
  })
}

var deferreds = $('input:checkbox:checked.checkprint').map(function(i, elem) {
  $.when(ajax_function()).then(function(data) {
    console.log('single call completed');
    return data;
  });
});

$.when.apply($, deferreds.get()).done(function() {
  console.log('all calls completed');
});
1
  • 1
    IMO it's bad idea of sending data over a every checkbox click, you can put a button, when user clicks the button read all those value and send it to server. Commented Feb 21, 2013 at 4:51

2 Answers 2

1

You can make your ajax calls synchronous.

function ajax_function() {
  return $.ajax({
    url: "submit.php",
    type: "POST",
    dataType: "json",
    data: form_data,
    cache: false,
    async:false
  })
}

option 2:

var totalnumber = $('input:checkbox:checked.checkprint').length;
var counter   = { t: 0 };
var deferreds = $('input:checkbox:checked.checkprint').map(function(i, elem) {
  $.when(ajax_function(totalnumber,counter)).then(function(data) {
    console.log('single call completed');
    return data;
  });
});

function ajax_function(totalnumber,counter) {
  return $.ajax({
    url: "submit.php",
    type: "POST",
    dataType: "json",
    data: form_data,
    cache: false,

  }).done(function( html ) {
    counter.t++;
    if (counter.t == totalnumber) {
         console.log('all calls completed');
    }
  });
}

Why counter.t, because objects are passed as references and we need to change the value of counter.t.

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

1 Comment

This works, but I'd like them to all fire off at the same time. When I change to async: false, it waits for each call to finish before moving on. I want them to all start together, and once all of them have completed to continue.
0

I think I accomplished what I was trying to do using ajaxStop (http://api.jquery.com/ajaxStop/)

$(document).delegate('#submit_all', 'click', function(e) {
  $('input:checkbox:checked.checkprint').each(function() {
    ajax_function();
  });
  $("#submit_all").one("ajaxStop", function() {
    console.log('all calls completed');
  });
});

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.