Disable inputs after submit to avoid double submission using JQuery and Ajax

Author posted by Jitendra on Posted on under category Categories HTML and tagged as Tags , with 1 Comment on Disable inputs after submit to avoid double submission using JQuery and Ajax

This article will explain the safe way to submit the forms using JQuery. It will avoid accidental double submission.

This tutorial will explain one of the ways to avoid accidental submissions of form using the JQuery and Ajax. While developing the web application this is the most common bug ignored by the newbies.

I will use the JQuery library and the Ajax to accomplish this behavior.

Disable inputs after submit to avoid double submission using JQuery
Disable inputs after submit to avoid double submission using JQuery

Html Code :

<form id="frm1">
     First Name:<input id="fName" name="fName" type="text" />
     Last Name:<input id="lName" name="lName" type="text" />
     Email:<input id="email" name="email" type="text" />
     <input id="submit" name="submit" type="submit" />
</form>

JQuery Code :

$(document).ready(function(){
    $("#frm1").submit(function(){
    //Disable form inputs
    $("input").attr("disabled", true);

    var fName = $("fName").val();
	var lName = $("lName").val();
	var email = $("email").val();

	var dataString = 'fName='+ fName + '&email=' + email + '&lName=' + lName;

    $.ajax({
    type: "POST",
    url: "addUser.php",
    data: dataString,
    success: function(){
    //Enable form inputs after form successfully submitted
    $("input").removeAttr('disabled');
    }
    });
    return false;
    });
});

Related posts

  • Sebastian

    Pretty smart solution. I like!