9

The below code blocks any non-ajax form from submitting.

$(this.form)
  .on('submit', function(event) {
    if (/* Some condition */) {
      event.preventDefault();
    }
  });

In Drupal 8, how can we block an Ajax form from being submitted?

Ajax forms do not trigger a form submit handler and I have not been able to block the click event on an Ajaxified form's submit buttons.

For reference, I am trying to fix Issue #3010084: Form submission finishes before file upload is complete

2 Answers 2

16

I found the solution here.

// Add submit handler to form.beforeSend.
// Update Drupal.Ajax.prototype.beforeSend only once.
if (typeof Drupal.Ajax !== 'undefined' && typeof Drupal.Ajax.prototype.beforeSubmitOriginal === 'undefined') {
  Drupal.Ajax.prototype.beforeSubmitOriginal = Drupal.Ajax.prototype.beforeSubmit;
  Drupal.Ajax.prototype.beforeSubmit = function (form_values, element_settings, options) {
    if (/* Custom condition */) {
      this.ajaxing = false;
      return false;
    }
    return this.beforeSubmitOriginal();
  };
}
2
  • Could you expand on your solution ? How do you implement this code ? I know php and JS but I don't know how AJAX is working in Drupal since I do mostly integration and theming. Commented Mar 26, 2019 at 9:41
  • I've used this code in my projet and it didn't work. Then, I've copied the code from your patch drupal.org/files/issues/2018-11-19/2952233-5.patch and it works. But I'm still interested in an explanation because I'm not sure to understand what it does. Commented Mar 26, 2019 at 15:35
0

Preventing a form submit while the form ajax handler is ongoing

   $(document).ajaxComplete(function(){
    $('#edit-next').removeAttr("disabled");
  });

  /**
   * prevent submit in case of ongoing ajax update
   */
  $(document).ajaxStart(function(event){
    event.preventDefault();
    $("#edit-next").attr("disabled", "disabled");
  } );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.