Jquery ajax on form submit prevent

Handle Jquery ajax on form submit

Hi, in this tutorial you will learn how to handle Jquery AJAX on form submit.

To handle a Jquery AJAX on form submit, first prevent the form submission.

Preventing form submission


<form action="" method="POST" id="formID">
    <input type="text" name="username">
    <input type="submit">
</form>
<script>
$(function(){
    $('#formID').submit(function(e){
        e.preventDefault();
        alert('Form submission has prevented');
    });
});
</script>

After Preventing the form submission now you can perform ajax.

<form action="http://example.com/" method="POST" id="formID">
    <input type="text" name="username">
    <input type="submit">
</form>
<script>
$(function(){
  $('#formID').submit(function(e){
    e.preventDefault();

    var formData = $(this).serialize();
    var actionURL = $(this).attr('action');

    $.ajax({
      url:actionURL,
      method:"POST",
      data:formData,
      success:function(data){
      console.log(data);
      },
      error:function(error){
      console.log(error);
      }
    });
  });
});
</script>

Leave a Reply