0

I have a few ajax requests that need to complete before I can submit a form.

How can I stall within a form.submit() call until all ajax requests are done?

var incompleteAjaxCalls = 0
// each ajax call runs incompleteAjaxCalls++ 
// followed by incompleteAjaxCalls-- upon completion
myForm.submit(function () {
 //sleep while incompleteAjaxCalls > 0;
});
asked Mar 20, 2014 at 15:41

1 Answer 1

4

prevent the form from submitting, then submit when ajax calls have completed

myForm.submit(function (e) {
 e.preventDefault();
 var self = this;
 $.when(
 $.ajax({url: 'ajax1'}),
 $.ajax({url: 'ajax2'})
 ).always(function() {
 self.submit();
 });
});

EDIT:

For array you could do

myForm.submit(function (e) {
 e.preventDefault();
 var self = this,
 xhr = [];
 xhr.push(
 $.ajax({url: 'ajax1'})
 );
 xhr.push(
 $.ajax({url: 'ajax2'})
 );
 $.when.apply(,ドル xhr).always(function() {
 self.submit();
 });
answered Mar 20, 2014 at 15:45
Sign up to request clarification or add additional context in comments.

5 Comments

Wouldn't that recurse indefinitely?
@Ramin - Nope, not if calling the native submit(), and not the jQuery submit(), there's an important difference there as triggering a native submit event with javascript does not trigger the jQuery event handler.
can you modify that code to be able to pass an array of deferreds instead?
Thanks. :) Why do you replace the always call with a then call in the second version? Based on the docs it seems like always will run pass or fail, but you then call only has a pass call back.
No particular reason, you could just as easily do $.when.apply(,ドル xhr).always(function() { ...

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.