Avoid Multiple Form Submissions – Best Practices

formsfrontendjavascript

What is the Magento way to avoid multiple form submissions? Ideally I'd like to disable the submit button on the form "submit" action and set a flag to check if the form has been already submitted.

But looking at Magento's VarienForm I've seen there is already a hook for the submit option, so I was dubious if it's ok to reuse that action.

Best Answer

Got it working now, what I've done is using jQuery to hook on myForm.submit() action as follows:

var myForm = new VarienForm('my-form-id', false);
var formAlreadySubmitted = false;
$j('#my-form-id').submit(function(e){
   if(myForm.validator.validate()){
      if(formAlreadySubmitted){
         e.preventDefault();
            return false;
         }
         var submitChildren = $j(this).find('button[type=submit]');
         submitChildren.attr('disabled', 'disabled');
         submitChildren.addClass('disabled');
         formAlreadySubmitted = true;
    }
});

Notice that I'm only disabling the submit button if the form passes Magento validation, so to give them the chance to correct the form if it's invalid.

Related Topic