0

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.

4
  • is page reloading when submit occurs? Have you checked if above event gets triggered? Any errors in console? Commented Apr 10, 2017 at 19:04
  • The form does get submitted, but the Ajax functions don't get executed. Commented Apr 10, 2017 at 19:05
  • ajaxOne should return the promise resulting from the call. Please show the code for at least one of those functions. Commented Apr 10, 2017 at 19:08
  • provided an answer but still a mystery why your form is submitting since you prevent default...check console for errors and make sure form exists when you call this code Commented Apr 10, 2017 at 19:12

2 Answers 2

2

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({...})    
}
Sign up to request clarification or add additional context in comments.

Comments

0

You have to pass as arguments

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

Take care of getting the responses.

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.