In this tutorial, we will see how to avoid duplicate submit using jQuery. While submitting a form via an AJAX function, the page will not refresh. So, the user interface will not show any progress about the server side execution taking place.
It will lead duplicate form to submit. To overcome this problem, we are avoiding double submits using jQuery.
Let us see this with an example. In this example, we have an HTML form and it is posted via AJAX. On processing the form submit action in server side, the submit button will be hidden to prevent multiple duplicates submits.
This is the HTML form to be submitted via jQuery AJAX.
<form id="frm" method="post">
<div class="input-group">Title <span class="title-validation validation-error"></span></div>
<div>
<input type="text" name="title" id="title" class="input-control" />
</div>
<div class="input-group">Description </div>
<div>
<textarea rows="5" name="description" id="description" class="input-control"></textarea>
</div>
<div id="submit-control">
<input type="button" name="btn-submit" id="btn-submit" value="submit" onClick="ajaxSubmit();"/>
</div>
</form>
On clicking the submit button, this jQuery script sends form data to PHP page via AJAX. While processing this AJAX request, it hides submit button and replaces it by showing progress notification message with loader.
function ajaxSubmit() {
var valid = true;
valid = checkEmpty($("#title"));
if(valid) {
var title = $("#title").val();
var description = $("#description").val();
$.ajax({
url: "process-ajax.php",
data:'title='+title+'&description='+description,
type: "POST",
beforeSend: function(){
$('#submit-control').html("<img src='LoaderIcon.gif' /> Ajax Request is Processing!");
},
success: function(data){
setInterval(function(){ $('#submit-control').html("Form submited Successfully!") },1000);
}
});
}
}