Preventing double-posting on a web page

A question was posed to the Arizona Groups list about how to prevent double-posting to a form on a web page.  My favorite solution to do this is set up a variable to track if the submit has happened yet or not.  The HTML needs to end up looking like this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
 <HEAD><title>FormTest</title></HEAD>
 <body>
  <script language="javascript">
   var haveSubmitted=false;
   function FirstSubmitOnly()
   {
    if(haveSubmitted) return false;

haveSubmitted=true; return true;    //we want the first click to occur. } </script> <form name="Form1" id="Form1" method="post" onsubmit="return FirstSubmitOnly();"> <input type="submit" name="ClickMe" value="Click Me!" id="ClickMe" /> </form> </body> </HTML>

In this case the function gets called from the onsubmit event handler on the form element.  But you could also put it on the onclick of the <input type="submit"> as well.  If you're using ASP.NET then this client-side event handler can be wired up in VB.NET with:

Button1.Attributes.Add("onclick","return FirstSubmitOnly();")

Equivalent C# is of course to just add a semicolon at the end of that line.  Hope you find this helpful!


Feedback

# re: Preventing double-posting on a web page

This shorter option was posted to the list by Michael Ryan:

<form ...
onsubmit="this.onsubmit=function(){return false;}; return true;">

The first time it's triggered it rewrites the function's definition, then returns true. Every time thereafter that rewritten definition for onsubmit() is hit, which returns false.
3/12/2006 6:14 PM | Lorin

# re: Preventing double-posting on a web page

This won't work if Javascript is disabled. 3/13/2006 6:31 AM | J

# re: (won't work if Javascript is disabled)

True, but quite rare! Those folks can't even use GMail. 3/13/2006 11:59 AM | Lorin

# re: Preventing double-posting on a web page

dasdasd 4/23/2007 6:26 AM | dasd

# re: Preventing double-posting on a web page

whic is the best?? 12/3/2007 10:58 PM | asd

Post a comment





 

Please add 7 and 4 and type the answer here:

News


Welcome to my blog.
Here's what we've got on the menu today:

Tag Cloud


Article Categories

Archives

Post Categories

Image Galleries

Syndication: