How to prevent double form submission

In this quick post i am going to tell you a very important issue which we faces every time we create a widely used form for our applications, You may have faced this issue with your applications form too. Because of this issue you may get duplicate entries in your database.

So here i’ll show you how to prevent your form from double submission. All you need to do is apply a few line jquery after clicking on submit button or form submit event.


For Normal Form

Suppose you have a contact us form

<form id="fm" action="">
Name: <input type="text" placeholder="Name"><br/>
Email: <input type="email" placeholder="Email"><br/>
Message: <textarea placeholder="Name"></textarea><br/>
<button id="sub">SUBMIT</button>	
</form>

And you need to disable submit button while form submit action apply. then you need to apply some jquery on form. But make sure you have already added jquery library on page.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

Finally apply some action whenever user perform form submit event, add disabled attribute on submit button on form submit action.

<script>
$(function(){
  $("#fm").submit(function(){
     $("#sub").html("Submitting please wait...");
     $("#sub").attr('disabled','disabled');
     //$("#sub").removeAttr('disabled');
  });
});
</script>

Jquery Ajax Form

In the case of ajax form you can completely remove the the submit button and add loading image.
And If you get any response from server side again show submit button and hide loading button.

Form

<form id="fm" action="">
Name: <input type="text" placeholder="Name"><br/>
Email: <input type="email" placeholder="Email"><br/>
Message: <textarea placeholder="Name"></textarea><br/>
<button id="sub" type="button">SUBMIT</button>
<div style="display:none;" id="loading"><img src="ajax-loader.gif">Submitting please wait...</div>	
</form>
<script>
$(function(){
 $("#sub").click(function(){
      var formData = $(this).serialize();
       $.ajax({
          url: "request.php",
          dataType: "json",
          data: formData,
          beforeSend:function(){
			$("#sub").hide();
			$("#loading").show();
		  },
          success: function( data ) {
            $("#sub").show();
            $("#loading").hide();
          },
          error: function (error) {
	    $("#sub").show();
            $("#loading").hide();
                console.log(error);
		  },
          timeout: 30000  
        });
  });
});
</script>

DEMO

DOWNLOAD



I hope you might have understand the point so far. This little code may prevent your database from duplicate entries.

If you like this post please don’t forget to subscribe my public notebook for more useful stuff