简体   繁体   中英

Prevent form data from submitting after http request

The following code prevents submitting the form data

$('#dataForm').submit(function (e) {
   e.preventDefault();
});

My problem is how to achieve that in case there's an ajax call which takes time to get response. So the form will not wait until the request get the response

$('#dataForm').submit(function (e) {
  ajaxCallAsPromise().then(function (data){
     if (data == true)
       {
         e.preventDefault(); //this will not work
       }
  });
  //any codes here works normally ..
});

My purpose to wait until get the request response then use-

e.preventDefault();

You will have to call preventDefault() immediately to stop the form submission. There's no way to avoid that as the AJAX call is asynchronous and you'll need to wait for it.

However you can call submit() on the form element itself after the AJAX call completes in order to subvert the jQuery event handler and allow the form to be sent to the server, like this:

$('#dataForm').submit(function(e) {
  e.preventDefault(); // stop the submission
  var form = this;

  ajaxCallAsPromise().then(function(data) {
    if (!data) { // if data is verified, submit the form again
      form.submit();
    } else {
      // presumably you want to tell the user the data is invalid here...
    }
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM