How to Prevent Users from Submitting a Form Twice

try out this code..

<input type="submit" name="btnADD" id="btnADD" value="ADD" onclick="this.disabled=true;this.value='Sending, please wait...';this.form.submit();" />

Once the form is submitted, attach a handler with jQuery that hijacks and "disables" the submit handler:

var $myForm = $("#my_form");
$myForm.submit(function(){
    $myForm.submit(function(){
        return false;
    });
});

Returning "false" from the submit handler will prevent the form from submitting. Disabling buttons can have weird effects on how the form is handled. This approach seems to basically lack side effects and works even on forms that have multiple submit buttons.


If you are working with java server side scripting and also using struts 2 then you refer this link which talks about on using token.

http://www.xinotes.org/notes/note/369/

A token should be generated and kept in session for the initial page render, when the request is submitted along with the token for the first time , in struts action run a thread with thread name as the token id and run the logic whatever the client has requested for , when client submit again the same request, check whether the thread is still running(thread.getcurrentthread().interrupted) if still running then send a client redirect 503.

And if you are not using any framework and looking for simple workout. You can take help of the

java.util.UUID.randomUUID();

Just put the random uuid in session and also in hidden form field and at other side(the jsp page where you are handling other work like storing data into database etc.) take out the uuid from session and hidden form field, If form field matches than proceed further, remove uuid from session and if not than it might be possible that the form has been resubmitted.

For your help i am writing some code snippet to give idea about how to achieve the thing.

<%
String formId=(java.util.UUID.randomUUID()).toString();
session.setAttribute(formId,formId);
%>
<input type='hidden' id='formId' name='formId' value='<%=formId%>'>

You can disable the button after clicking or hide it.

<input type="submit" name="btnADD" id="btnADD" value="ADD" onclick="disableButton(this)"/>

js :

 function disableButton(button) {
     button.disabled = true;
     button.value = "submitting...."
     button.form.submit();
}