How to prevent form from submitting multiple times from client side? - javascript

Sometimes when the response is slow, one might click the submit button multiple times.
How to prevent this from happening?

Use unobtrusive javascript to disable the submit event on the form after it has already been submitted. Here is an example using jQuery.
EDIT: Fixed issue with submitting a form without clicking the submit button. Thanks, ichiban.
$("body").on("submit", "form", function() {
$(this).submit(function() {
return false;
});
return true;
});

I tried vanstee's solution along with asp mvc 3 unobtrusive validation, and if client validation fails, code is still run, and form submit is disabled for good. I'm not able to resubmit after correcting fields. (see bjan's comment)
So I modified vanstee's script like this:
$("form").submit(function () {
if ($(this).valid()) {
$(this).submit(function () {
return false;
});
return true;
}
else {
return false;
}
});

Client side form submission control can be achieved quite elegantly by having the onsubmit handler hide the submit button and replace it with a loading animation. That way the user gets immediate visual feedback in the same spot where his action (the click) happened. At the same time you prevent the form from being submitted another time.
If you submit the form via XHR keep in mind that you also have to handle submission errors, for example a timeout. You would have to display the submit button again because the user needs to resubmit the form.
On another note, llimllib brings up a very valid point. All form validation must happen server side. This includes multiple submission checks. Never trust the client! This is not only a case if javascript is disabled. You must keep in mind that all client side code can be modified. It is somewhat difficult to imagine but the html/javascript talking to your server is not necessarily the html/javascript you have written.
As llimllib suggests, generate the form with an identifier that is unique for that form and put it in a hidden input field. Store that identifier. When receiving form data only process it when the identifier matches. (Also linking the identifier to the users session and match that, as well, for extra security.) After the data processing delete the identifier.
Of course, once in a while, you'd need to clean up the identifiers for which never any form data was submitted. But most probably your website already employs some sort of "garbage collection" mechanism.

Here's simple way to do that:
<form onsubmit="return checkBeforeSubmit()">
some input:<input type="text">
<input type="submit" value="submit" />
</form>
<script type="text/javascript">
var wasSubmitted = false;
function checkBeforeSubmit(){
if(!wasSubmitted) {
wasSubmitted = true;
return wasSubmitted;
}
return false;
}
</script>

<form onsubmit="if(submitted) return false; submitted = true; return true">

The most simple answer to this question as asked: "Sometimes when the response is slow, one might click the submit button multiple times. How to prevent this from happening?"
Just Disable the form submit button, like below code.
<form ... onsubmit="buttonName.disabled=true; return true;">
<input type="submit" name="buttonName" value="Submit">
</form>
It will disable the submit button, on first click for submitting. Also if you have some validation rules, then it will works fine. Hope it will help.

Create a unique identifier (for example, you can hash the current time), and make it a hidden input on the form. On the server side, check the unique identifier of each form submission; if you've already received that hash then you've got a repeat submission. The only way for the user to re-submit is to reload the form page.
edit: relying on javascript is not a good idea, so you all can keep upvoting those ideas but some users won't have it enabled. The correct answer is to not trust user input on the server side.

Disable the submit button soon after a click. Make sure you handle validations properly. Also keep an intermediate page for all processing or DB operations and then redirect to next page. THis makes sure that Refreshing the second page does not do another processing.

You could also display a progress bar or a spinner to indicate that the form is processing.

Using JQuery you can do:
$('input:submit').click( function() { this.disabled = true } );
&
$('input:submit').keypress( function(e) {
if (e.which == 13) {
this.disabled = true
}
}
);

I know you tagged your question with 'javascript' but here's a solution that do not depends on javascript at all:
It's a webapp pattern named PRG, and here's a good article that describes it

You can prevent multiple submit simply with :
var Workin = false;
$('form').submit(function()
{
if(Workin) return false;
Workin =true;
// codes here.
// Once you finish turn the Workin variable into false
// to enable the submit event again
Workin = false;
});

On the client side, you should disable the submit button once the form is submitted with javascript code like as the method provided by #vanstee and #chaos.
But there is a problem for network lag or javascript-disabled situation where you shouldn't rely on the JS to prevent this from happening.
So, on the server-side, you should check the repeated submission from the same clients and omit the repeated one which seems a false attempt from the user.

You can try safeform jquery plugin.
$('#example').safeform({
timeout: 5000, // disable form on 5 sec. after submit
submit: function(event) {
// put here validation and ajax stuff...
// no need to wait for timeout, re-enable the form ASAP
$(this).safeform('complete');
return false;
}
})

The simpliest and elegant solution for me:
function checkForm(form) // Submit button clicked
{
form.myButton.disabled = true;
form.myButton.value = "Please wait...";
return true;
}
<form method="POST" action="..." onsubmit="return checkForm(this);">
...
<input type="submit" name="myButton" value="Submit">
</form>
Link for more...

Use this code in your form.it will handle multiple clicks.
<script type="text/javascript">
$(document).ready(function() {
$("form").submit(function() {
$(this).submit(function() {
return false;
});
return true;
});
});
</script>
it will work for sure.

This allow submit every 2 seconds. In case of front validation.
$(document).ready(function() {
$('form[debounce]').submit(function(e) {
const submiting = !!$(this).data('submiting');
if(!submiting) {
$(this).data('submiting', true);
setTimeout(() => {
$(this).data('submiting', false);
}, 2000);
return true;
}
e.preventDefault();
return false;
});
})

the best way to prevent multiple from submission is this
just pass the button id in the method.
function DisableButton() {
document.getElementById("btnPostJob").disabled = true;
}
window.onbeforeunload = DisableButton;

To do this using javascript is bit easy. Following is the code which will give desired functionality :
$('#disable').on('click', function(){
$('#disable').attr("disabled", true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="disable">Disable Me!</button>

Most simple solutions is that disable the button on click, enable it after the operation completes. To check similar solution on jsfiddle :
[click here][1]
And you can find some other solution on this answer.

This works very fine for me. It submit the farm and make button disable and after 2 sec active the button.
<button id="submit" type="submit" onclick="submitLimit()">Yes</button>
function submitLimit() {
var btn = document.getElementById('submit')
setTimeout(function() {
btn.setAttribute('disabled', 'disabled');
}, 1);
setTimeout(function() {
btn.removeAttribute('disabled');
}, 2000);}
In ECMA6 Syntex
function submitLimit() {
submitBtn = document.getElementById('submit');
setTimeout(() => { submitBtn.setAttribute('disabled', 'disabled') }, 1);
setTimeout(() => { submitBtn.removeAttribute('disabled') }, 4000);}

Just to add to the possible answers without bypassing browser input validation
$( document ).ready(function() {
$('.btn-submit').on('click', function() {
if(this.form.checkValidity()) {
$(this).attr("disabled", "disabled");
$(this).val("Submitting...");
this.form.submit();
}
});
});

An alternative to what was proposed before is:
jQuery('form').submit(function(){
$(this).find(':submit').attr( 'disabled','disabled' );
//the rest of your code
});

<h3>Form</h3>
<form action='' id='theform' >
<div class='row'>
<div class="form-group col-md-4">
<label for="name">Name:</label>
<input type='text' name='name' class='form-control'/>
</div>
</div>
<div class='row'>
<div class="form-group col-md-4">
<label for="email">Email:</label>
<input type='text' name='email' class='form-control'/>
</div>
</div>
<div class='row'>
<div class="form-group col-md-4">
<input class='btn btn-primary pull-right' type="button" value="Submit" id='btnsubmit' />
</div>
</div>
</form>
<script>
$(function()
{
$('#btnsubmit').on('click',function()
{
$(this).val('Please wait ...')
.attr('disabled','disabled');
$('#theform').submit();
});
});
</script>

This is a clean Javascript code that prevents multiple valid submissions:
<script>
var form = document.querySelector('form');
form.onsubmit = function(e){
if(form.reportValidity())
// if form is valid, prevent future submissions by returning false.
form.onsubmit = (e)=> false;
return true;
}
</script>

Related

How to change form url parameter on submit?

I have this form for processing..
<form action="driver.php" method="GET">
<input type="text" placeholder="Search" id="search" name="n">
<button type="submit">Submit</button>
</form>
by default the url is http://sites.com/driver.php?n=typedname
so i did modifications in .htaccess and convert it to http://sites.com/driver/typedname for SEO friendly urls modrewrite issue - 404 error thanks to anubhava
everything is well, but the problem now comes when I type and click the submit button, it will go to http://sites.com/driver.php?n=typedname
so how can I make it to go this url http://sites.com/driver/typedname instead after clicking submit?
I think javascript can do this, so i tagged it, hope im not wrong.
thanks.
jQuery
$('button[type=submit]').click(function(e){
e.preventDefault();
e.stopPropagation();
window.location = "http://sites.com/driver/" + $('#search').val();
return false;
});
or
$('form').submit(function(e) { // you really need to class/ID your form
// all that code
});
Now this is quick and dirty to give you the idea. You'd of course want to sanitize your input (good idea to do that on the front-end as well as the back-end).
You will have to handle form submit event yourself. Something like this:
document.querySelector('form').addEventListener('submit', function(e) {
e.preventDefault();
location.href = '/driver/' + this.elements.n.value;
}, false);

Bootstrap or jquery stopping form SUBMIT

Tired to make this parallax with bootstrap and jquery.. but FORM is not submitting while this code works fine separately if I run.. If someone can help me out in this..
Here is page : http://cellsouq.com/xtra/co/ (complete code)
Click on OPPORTUNITIES > FRANCHISE (on top navigation)
Click on APPLY ... it will scroll to FORM
Form is something like that with javascript
<script>
function funcFranchise() {
alert('Submitted Successfull');
// To validate form elements
}
</script>
<form onSubmit="return funcFranchise(this)" class="form-horizontal" >
...
<input type="submit" value="Submit Request" class="btn bg-primary" >
</form>
If i remove Bootstrap it works fine. In whole code somewhere submit EVENT is blocked not sure... Please help me out..
You should return either true or false upon the completion your validations. So try like;
<script>
function funcFranchise() {
alert('Submitted Successfull');
// To validate form elements
return true;
}
</script>
try this:
function funcFranchise() {
alert('Submitted Successfull');
// To validate form elements
$('.form-horizontal').submit();
}

Infinite form submit with $(document).ready

i want to create a post form it'll get data from my url and post it to my database.
When i clicked the "Add" buton its working fine but when i try to add with $(document).ready function, I'm getting infinite loop. (My goal is submitting form every time i execute the file)
I've no knowlage about jquery and Im using this code:
<script type="text/javascript">
$(document).ready(function () {
document.forms["form1"].submit();
});
</script>
How can I get rid off infinite loop?
I'm guessing your form does not have action-attribute, hence it posts to itself. Add action attribute to the page you want to post to:
<form action="mypage.html"....
You will have to use cookie to store first load information and check it before submitting form. Set the expire time as per your project requirement. Before using jQuery cookie, you have add cookie plugin after jQuery library.
jQuery Cookie: jQuery Cookie plugin.
<script type="text/javascript">
$(document).ready(function () {
if (! $.cookie("cookieName")){
document.forms["form1"].submit(); // do your stuff
$.cookie("cookieName", "firstSet", {"expires" : 7}); // set cookie now
}
});
</script>
Hope will help!
Can you try?
$(document).one("ready",function(){
// submit form here
});
Use below code.
<form action="yourformname.html" method="post" enctype="multipart/form-data">
</form>
<input type="submit" value="Submit">
If there is any file upload control, then use enctype in form tag.
Maybe a flag can do the job.
var flag = true;
$(document).ready(function(){
if(flag){
// submit code here
flag = false;
}
});
Inside your form paste this line,
<input type="hidden" name="ispost" value="0" id="ispost">
And in jQuery add this, your issue will be resolved
<script type="text/javascript">
$(document).ready(function() {
if($('#ispost').val() != 'submit')
{
$('#ispost').val('submit');
$('#form1').submit();
}
});
</script>

html form does not respond to hitting "enter" button

I have this html form, which does not actually sends data to a php file, buts sends data to a javascipt function.
Works fine if I hit the "Go" button, but if I choose something and hit "enter", does not work. Does not send the data to the function, that is.
I have made other forms with the same pattern, to send data to a javascript function in the same file and they work . This one refuses.
How do I fix this? Thanks
<form id="boroughform" enctype="multipart/form-data" method="post" action="#" onSubmit="return goborough(this); return false;" >
Choose borough:<br/>
<select name="boroughselect" id="boroughselect" >
<option selected value=" ">Choose...</option>
//fill the options with the results of a query performed eariler - works
<?php
for ($v=0; $v< sizeof($borough) ; $v++)
{echo '"<option value="'.$bid[$v].','.$bboxa[$v].','.$bboxb[$v].','.$bboxc[$v].','.$bboxd[$v].'" >'.$borough[$v].'</option>';}
?>
</select><br/>
<input type="submit" value="Go" name="postbor" class="formButton">
</form>
//the js
function goborough(g){
var binfo=g.elements['boroughselect'].value;
if(binfo!=" "){
//some cool openlayers staff here
return false;
}
else{alert('You have not chosen a borough !!! ');return false;}
}
In your form element (the select) try this,
onkeypress="if(event.keyCode==13) {this.submit();}"
Or use jquery,
$(document).ready(function() {
$("input").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
$("#broughtform").submit();
}
});
});
Your problem is not in the code, but in that the select element has reserved the enter key for other purposes, see why doesn't hitting enter when a SELECT is focused submit the form?
Apply an onkeypress event to the select element to change this default behaviour.
If you're sure that everything is fine and it should go. Then you might use this:
onkeydown(submitform)
In the form tag, and in the function you should use this:
function submitform () {
if(event.keyCode == 13) {
// submit the form.. as enter key code is 13.
}
}
I am not sure why its not working. You should try to read and look at the console from the browser, it must tell you what is the error. Try doing that by pressing F12 in your Browser. You will get an error code there, try Googling it, or sharing it in the Question.
You should return true to submit the form but you are always returning false, return false and it prevents the submission.
JS:
function goborough(g){
var binfo=g.elements['boroughselect'].value;
if(binfo!=" "){
//some cool openlayers staff here
return true;
}
else{
alert('You have not chosen a borough !!! ');
return false;
}
}
HTML:
You have this
onSubmit="return goborough(this); return false;"
but, it should be
onSubmit="return goborough(this);"

Can JQuery.Validate plugin prevent submission of an Ajax form

I am using the JQuery form plugin (http://malsup.com/jquery/form/) to handle the ajax submission of a form. I also have JQuery.Validate (http://docs.jquery.com/Plugins/Validation) plugged in for my client side validation.
What I am seeing is that the validation fails when I expect it to however it does not stop the form from submitting. When I was using a traditional form (i.e. non-ajax) the validation failing prevented the form for submitting at all.... which is my desired behaviour.
I know that the validation is hooked up correctly as the validation messages still appear after the ajax submit has happened.
So what I am I missing that is preventing my desired behaviour? Sample code below....
<form id="searchForm" method="post" action="/User/GetDetails">
<input id="username" name="username" type="text" value="user.name" />
<input id="submit" name="submit" type="submit" value="Search" />
</form>
<div id="detailsView">
</div>
<script type="text/javascript">
var options = {
target: '#detailsView'
};
$('#searchForm').ajaxForm(options);
$('#searchForm').validate({
rules: {
username: {required:true}},
messages: {
username: {required:"Username is a required field."}}
});
</script>
You need to add a callback function for use with the beforeSubmit event when initializing the ajaxForm():
var options = {
beforeSubmit: function() {
return $('#searchForm').validate().form();
},
target: '#detailsView'
};
Now it knows to check the result of the validation before it will submit the page.
... well it's been a while so my situation has changed a little. Currently I have a submitHandler option passed to the Validate() plugin. In that handler I manually use ajaxSubmit. More a workaround than an answer I guess. Hope that helps.
http://jquery.bassistance.de/validate/demo/ajaxSubmit-intergration-demo.html
var v = jQuery("#form").validate({
submitHandler: function(form) {
jQuery(form).ajaxSubmit({target: "#result"});
}
});
$('#contactform').ajaxForm({
success : FormSendResponse,
beforeSubmit: function(){
return $("#contactform").valid();
}
});
$("#contactform").validate();
Above code worked fine for me.
Also make sure all of your input fields have a "name" attribute as well as an "id" attribute. I noticed the jquery validation plugin doesn't function correctly without these.
ok, this is an old question but i will put our solution here for posterity. i personally classify this one as a hack-trocity, but at least it's not a hack-tacu-manjaro
<script type="text/javascript">
var options = {
target: '#detailsView'
};
// -- "solution" --
$('#searchForm').submit(function(event) {
this.preventDefault(event); // our env actually monkey patches preventDefault
// impl your own prevent default here
// basically the idea is to bind a prevent default
// stopper on the form's submit event
});
// -- end --
$('#searchForm').ajaxForm(options);
$('#searchForm').validate({
rules: {
username: {required:true}},
messages: {
username: {required:"Username is a required field."}}
});
</script>
Just as a first pass, I'm wondering why the line
$("form").validate({
doesn't refer to $("searchform"). I haven't looked this up, or tried it, but that just seems to be a mismatch. Wouldn't you want to call validate on the appropriate form?
Anyway, if this is completely wrong, then the error isn't immediately obvious. :)
May be a
return false;
on the form will help?
:)
I mean:
<form id="searchForm" method="post" action="/User/GetDetails" onSubmit="return false;">

Categories