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
TheOne
11.2k21 gold badges87 silver badges122 bronze badges
1 Answer 1
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
adeneo
319k29 gold badges410 silver badges392 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
TheOne
Wouldn't that recurse indefinitely?
adeneo
@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.TheOne
can you modify that code to be able to pass an array of deferreds instead?
TheOne
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.adeneo
No particular reason, you could just as easily do
$.when.apply(,ドル xhr).always(function() { ...lang-js