简体   繁体   中英

Need to avoid submit form twice to the server when user double clicks on submit button

Using jquery validatye plugin, I am validating and submitting the form to the server which stores form data in data base. The issue is when user double clicks on the form, multiple requests are going in and its submitting twice to the server and its resulting in multiple recors with same data in data base. I want to avoid this scenario. I want the form to be submitted only once even though the user clicks twice on the submit button.

Code:

            var validator = jQuery("#form")
              .validate(
                {

                    errorClass : "invalid",
                    validClass : "valid",
                    submitHandler : function() {

                        //function to submit form to client
                        submitFormtoClient();


                    },

When the user clicks on submit the form is validated and then submit handler function is called. I want this to be called only once even though the submit button has been clicked twice

The submitHandler is only fired after the form is valid AND the submit button is clicked. If you disable the submit button immediately after it's first clicked, it would be impossible to have a double-click situation.

submitHandler: function(form) {  // form is valid

    // disable submit button since it was already clicked and submit is happening next
    $('#your-submit-button').prop('disabled', true);

    // function to submit form to client
    submitFormtoClient();

}

Whenever you determine that the form is valid and should be submitted, in on "submit", before you return true , you can set the form's submit button to be disabled, and it should never submit twice.

If you determine it shouldn't submit, you'd return false.

$('.foo-form').on("submit", function(event){
    $(this).children('button[type=submit]').prop('disabled', true);
    return true;
}

In this case, I used button[type=submit] but you can use input[type=submit] as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM