Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent form submission and manually submit later inside an async submit jQuery function

Tags:

javascript

Here's a basic version of what I'm trying to achieve.

Since I have some awaits in the function, I use async

$(document).on('submit', '.applicationForm', async function(e) {
    do some validation

    if (!valid) {
        return true;
    }

    return false;

});

But the form submits in the end. I've even tried adding e.preventDefault() and that didn't work either. Is this all because of the async bit?

like image 562
hadyfarhat Avatar asked Oct 29 '25 13:10

hadyfarhat


2 Answers

Functions marked as async always return a Promise, so won't return false.

They also return immediately, so e.preventDefault won't work because it executes too late.


You can't wait for asyncronous code to run before cancelling the event.

Instead:

  • Don't use an async function
  • Always e.preventDefault
  • Restart the submission (with the_form.submit()) if the validation passes

or

Do the validation as the user interacts with the form. Set a flag to valid or invalid as they go. When the submit button is clicked, check the status of the flag.

like image 114
Quentin Avatar answered Nov 01 '25 03:11

Quentin


An async function will automatically return a Promise, and since a promise that resolves to false isn't the same thing as false, the form will submit - only if exactly false is returned will the form not submit.

Always return false instead, and submit the form manually if validation passes:

$(document).on('submit', '.applicationForm', function(e) {
  checkValidity(this);
  return false;
});
async function checkValidity(form) {
  // do some validation
  if (valid) {
    $(this).trigger("submit");
  }
}
like image 45
CertainPerformance Avatar answered Nov 01 '25 02:11

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!