Rick Helston
Rick Helston

Reputation: 763

Using when() to Run Multiple Ajax Functions

Using jQuery when(), I am trying to run multiple Ajax functions on a form submit, wait until they get their responses and when done, finally submit form. My code is:

$('form[name="regForm"]').on('submit', function( e ) {
    e.preventDefault();

    $.when( function () {
        ajaxOne();
        ajaxTwo();
        ajaxThree();
    }
    ).done(function() {
        $('form[name="regForm"]').unbind('submit').submit();
    });
});

The form gets submitted but the Ajax functions never trigger. What am I doing wrong? Thanks for any help.

Upvotes: 0

Views: 38

Answers (2)

deostroll
deostroll

Reputation: 11975

You have to pass as arguments

$.when.apply($, arrayOfDefferds).done(doStuff);

Take care of getting the responses.

Upvotes: 0

charlietfl
charlietfl

Reputation: 171669

You have written $.when() incorrectly

Each ajax call promise should be an argument (or in jQuery 3+ can be array of promises)

$(function(){
    $('form[name="regForm"]').on('submit', function( e ) {
        e.preventDefault();

        $.when( ajaxOne(), ajaxTwo(),  ajaxThree()   
        ).done(function() {
            $('form[name="regForm"]').unbind('submit').submit();
        });
    });
});

This also assumes that form selector is correct and that each of the ajax functions returns a $.ajax promise something like

function ajaxOne()(
  return $.ajax({...})    
}

Upvotes: 2

Related Questions