Question

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;
});
Was it helpful?

Solution

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();
    });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top