[英]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.使用 jquery validatye 插件,我正在验证表单并将其提交到将表单数据存储在数据库中的服务器。 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. submitHandler
仅在表单有效并且单击提交按钮后才会触发。 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.每当您确定表单有效并且应该提交时,在“提交”时,在return true
之前,您可以将表单的提交按钮设置为禁用,并且它不应该提交两次。
If you determine it shouldn't submit, you'd return false.如果你确定它不应该提交,你会返回 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.在这种情况下,我使用了button[type=submit]
但你也可以使用input[type=submit]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.