Gowire
Gowire

Reputation: 1060

How can I submit form data after preventDefault is called?

I am a little confused on how to take control of the submit event in a form, and I have tried to find a simple answer here.

I want to validate the form input before sending the form data to the form action scrip. I have tried to solve this by capturing the submit event, calling a validation script with Ajax, and if the validation succeeds I want the actual form procedure to be called. But I'm not sure how to proceed. Simply using location.replace("action.php") seems to fail (I guess that the form values aren't sent).

Here's the conceptual code:

$("form").on("submit", function(event) {
  event.preventDefault();
  
  data = {
    the_input_val: $("#input_to_be_validated").val()
  };
  
  $.post("ajax_validate_input.php", data, function(data, status) {
    if (status == "success") {
      if (data == "invalid") {
        alert("Invalid input");
        // Form data is not sent... as expected
      } else {
        // Here I want to send the form data. But the event.preventDefault() prevents it from happening
        // What do I put here to call the form's 'action' script with form data? 
      }
    }
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="action.php">
  <input id="input_to_be_validated" name="my_input" type="text">
  <button type="submit" name="submit">Submit</button>
</form>

Upvotes: 2

Views: 3272

Answers (2)

Emiel Zuurbier
Emiel Zuurbier

Reputation: 20934

Call the submit() method on an HTMLFormElement to manually submit the form without passing through the submit event again.

The form can be retrieved by reading out the target property of the event object.

Though, to make this work, lose the name="submit" value on your button, as this will cause an error trying to submit with the method.

const $form = $("form");

$form.on("submit", function(event) {
  event.preventDefault();
  
  const data = {
    the_input_val: $("#input_to_be_validated").val()
  };
  
  $.post("ajax_validate_input.php", data, function(data, status) {
    if (status == "success") {
      if (data == "invalid") {
        alert("Invalid input");
        // Form data is not sent... as expected
      } else {
        event.target.submit();
      }
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="action.php">
  <input id="input_to_be_validated" name="my_input" type="text">
  <button type="submit">Submit</button>
</form>

Upvotes: 1

AndrewL64
AndrewL64

Reputation: 16301

You can use the submit() method like this:

if (status == "success") {
  if (data == "invalid") {
    alert("Invalid input");
    // Form data is not sent... as expected
  } else {
    event.submit();
  }
}

Upvotes: 0

Related Questions