Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I prevent form submission until multiple ajax calls have finished? jquery

Following on from a previous question where I asked about disabling a submit button until all ajax calls have finished returning...

It seems that people are still managing to submit the form even with the button disabled and a warning sign. I guess it could be from pressing 'enter' in a text input.

How do I go about disabling the whole form, rather than just the submit button?

The code so far is:

// if we're waiting for any ajax to complete we need to disable the submit
$(document).ajaxStart(function() {
  $(".ajaxbutton").attr("disabled", "disabled");
  // if it's taken longer than 250ms display waiting message
  timer = setTimeout(function() {
    $('#processingAlert').html(' ...please wait one moment');
    $('#processingAlert').show();
  }, 250);
})
$(document).ajaxComplete(function() {
  $(".ajaxbutton").removeAttr("disabled");
    $('#processingAlert').hide();
    // cancel showing the message when the ajax call completes.
clearTimeout(timer);
});

One other thing that I should mention which could be causing a problem is that there are multiple ajax calls happening at the same time, EG one div receives hidden inputs and another div elsewhere on the page shows a price total for instance.

Would the fact that some ajax calls are completing quickly negate the disabling effect of ajaxStart? EG ajax call1 and ajax call2 both fire the ajaxStart - call1 finishes really quickly, would it re-enable the form while we are waiting for call2 to complete?

Is there a better way of doing this where we could simply test if ALL ajax calls have completed?

like image 226
Ashley Avatar asked Feb 18 '10 16:02

Ashley


1 Answers

You can add an event handler for the submit event of the form. The event handler can check if the submit is allowable yet, and abort if not. Here's some docs: http://api.jquery.com/submit/

Note that if javascript on the page calls .click() on one of the form submission buttons, the form will be submitted without calling your .submit() handler. This is a weird jQuery issue (http://groups.google.com/group/jquery-en/browse_thread/thread/1317bfd4e3a8b233?pli=1) which I guess the jQuery folks don't consider a bug. There may be other cases like this, I hope not.

If you're using ASP.NET, depending on whats on the form, ASP.NET may inject a "__doPostBack" function. You may need to hook that function instead by redefining it with some custom code that calls the original.

like image 127
Frank Schwieterman Avatar answered Nov 01 '22 10:11

Frank Schwieterman