Is it possible to use jQuery's .when() with a forEach loop of ajax calls? -


i have several forms post server @ once. then, want listen of them complete. if hear them complete successfully, take 1 action and, if see 1 fail, take different action.

i believe should use jquery's .when(): http://api.jquery.com/jquery.when/

this post on stackoverflow shows example on how when have of ajaxrequests explicitly defined: wait until jquery ajax requests done? wondering if possible achieve same effect loop somehow?

i have code, not wait complete:

_.each($('form'), function (form) {             var $form = $(form);              if ($form.valid()) {                 //  post form data                 $.ajax({                     url: $form.attr('action'),                     type: $form.attr('method'),                     data: getformdata($form),                     success: function () {}                     error: function(){}                 });             }         }); 

edit: while i've accepted answer.. worth noting correct 'answer' changing design requirements. realized extremely difficult undo 1 transaction if failed, had keep transactions in same state. led down path beetroot had suggested, creating 1 giant model, added ton of other complexities. such, have user save before changing between tabs.

you can use jquery.when so;

jquery.when.apply(jquery, $('form').map(function () {     var $form = $(form);      if ($form.valid()) {         //  post form data         $.ajax({             url: $form.attr('action'),             type: $form.attr('method'),             data: getformdata($form),             success: function () {}             error: function () {}         });     }      // otherwise don't anything. })).done(function (form1ajax, form2ajax, formnajax) {     // complete     }).fail(function (form1ajax, form2ajax, formnajax) {     // 1 failed }); 

unfortunately, jquery.when expects each deferred given separate parameter, rather array of deferreds; why we're jumping through hoops apply.

note behaviour of map(); not add element resultant array if undefined or null returned.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -