omg
omg

Reputation: 139872

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

Sometimes when the response is slow, one might click the submit button multiple times.

How to prevent this from happening?

Upvotes: 122

Views: 175059

Answers (25)

Omar Lajam
Omar Lajam

Reputation: 61

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>

Upvotes: 0

llimllib
llimllib

Reputation: 3702

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.

Upvotes: 11

danish_wani
danish_wani

Reputation: 872

<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>

Upvotes: 0

An alternative to what was proposed before is:

jQuery('form').submit(function(){
     $(this).find(':submit').attr( 'disabled','disabled' );
     //the rest of your code
});

Upvotes: 0

Aurel
Aurel

Reputation: 3740

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;
    });
})

Upvotes: 1

vanstee
vanstee

Reputation:

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;
});

Upvotes: 111

m irina
m irina

Reputation: 471

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;
    }
});

Upvotes: 47

Roi
Roi

Reputation: 565

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();
        }
    });
});

Upvotes: 0

Bachas
Bachas

Reputation: 243

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.

Upvotes: 1

Solis
Solis

Reputation: 11

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...

Upvotes: 1

Awais Jameel
Awais Jameel

Reputation: 2206

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);}

Upvotes: 0

Kalyani
Kalyani

Reputation: 411

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.

Upvotes: 0

Rish
Rish

Reputation: 1383

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>

Upvotes: 0

Imran Khan
Imran Khan

Reputation: 2401

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.

Upvotes: 10

Max Kamenkov
Max Kamenkov

Reputation: 2598

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;
    }
})

Upvotes: 3

user2427182
user2427182

Reputation: 31

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; 

Upvotes: 0

Alpha
Alpha

Reputation: 453

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;

});

Upvotes: 4

steveyang
steveyang

Reputation: 9298

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.

Upvotes: 4

Pablo Fernandez
Pablo Fernandez

Reputation: 105220

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

Upvotes: 4

Rob
Rob

Reputation: 509

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.

Upvotes: 26

Boris Gu&#233;ry
Boris Gu&#233;ry

Reputation: 47585

Using JQuery you can do:

$('input:submit').click( function() { this.disabled = true } );

&

   $('input:submit').keypress( function(e) {
     if (e.which == 13) {
        this.disabled = true 
     } 
    }
   );

Upvotes: 5

ichiban
ichiban

Reputation: 6200

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>

Upvotes: 17

Tony Borf
Tony Borf

Reputation: 4660

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

Upvotes: 5

Shoban
Shoban

Reputation: 23016

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.

Upvotes: 8

chaos
chaos

Reputation: 124297

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

Upvotes: 16

Related Questions