7

Any ideas how you might use JQuery's deferred methods with a function that detects all changed forms and submits each one as an Ajax post?

I can get the same thing working if I just list a load of form submissions but if I use...

$('form.changed').each(function(){
  return $(this).submitWithAjax();
});

A fuller version of the code that I'm trying to get working is here... at JS Fiddle

Thanks in advance!

1
  • Could you clarify your question? I'm not sure I understand (but I'm pretty sure my answer is off base ...) Commented May 28, 2011 at 16:54

2 Answers 2

17

Instead of ".each()", use ".map()":

var deferreds = $('form.changed').map(function(i, elem) {
  return $(this).submitWithAjax();
});

$.when.apply(null, deferreds.get()).then(function() { ... });

The "$.when()" thing lets you bundle up a bunch of deferred objects and wait for all of them to succeed (or for any to fail — note the difference there). It normally allows an arbitrary number of arguments, but since we've got an array I used "apply()".

Note that I've only used this stuff lightly, so read the jQuery API docs to double check :-) edit — also upon re-reading your question, I may have misunderstood you.

Sign up to request clarification or add additional context in comments.

2 Comments

This works perfectly. Thanks for your help. Just trying to understand why it works now.
The "Deferred" feature is one of those things that's pretty simple, but I agree that it's really hard to totally "get" exactly how the mechanism works :-)
0

Delegating the change event to the form fields could solve your problem here.

$('form').delegate('input[type=text], input[type=radio], select', 'change', 
function(evt){
    // your submits here
    console.log('changed!')
});

1 Comment

Thanks for your response but detecting the changes on the form wasn't the problem. '$("form :input").live('change', function(){ // If a form input changes $(this).closest('form').addClass("changed"); });'

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.