Knowledge Base Articles » KB100220: Preventing users from re-submitting a form.

A common question asked at DevGuru.com is "How do I disable the browser's Back button?". The simple answer is "You can't". Browser security settings prevent client-side code from disabling any buttons or menu items in a browser window that is currently open.

However, if the real goal is to prevent a user from re-submitting a form then here is one possible solution. It involves using cookies to determine if the form has already been submitted and if so display an appropriate message.

The first step is to add code to the page that contains the form (we'll assume this is called Form.asp) that will prevent the page from being cached by the browser. Refer to Knowledge Base article A100204: 'ASP pages hot off the server: prevent cached pages from loading.' for details of how to do this. Next an IF clause needs to be added to the page to perform a server-side check to determine whether or not the form has already been submitted. The form in our example will only be displayed prior to a submission. If Form.asp is requested again after the form has been submitted, an appropriate message is displayed notifying the user that they can only submit the form once.

The following is the source code for Form.asp:

<%
Response.AddHeader "Pragma", "no-cache"
Response.AddHeader "cache-control", "no-store"

'Display appropriate message if form has already been submitted
If Request.Cookies("FormSubmitted") = "True" Then
%>

<html>
<head>
<title>Submit Only Once</title>
</head>
<body>
Look closely, notice anything missing?<br>
No form.
</body>
</html>

<%
'Display form
Else
%>

<html>
<head>
<title>Submit Only Once</title>
</head>
<body>
<form name="FormMain" action="Results" method="post">
Click the Submit button to see this code in action.
<input type="submit" value="Submit">
</form>
</body>
</html>

<%
End If
%>


For the above code to work, a cookie ("FormSubmitted") needs to be set in the page that handles the submission of the form - in this example, we'll call the page that handles the form submission, Results. The cookie will remain in place for the "life of the browser" (until the user closes the current browser session). The example could be expanded, if desired, to prevent the user from re-submitting the form even after the life of the current browser by setting an expicit expiration date for the cookie.

The following is the source code for Results:

<%
Response.Cookies("FormSubmitted") = "True"
%>

<html>
<head>
<title>Submit Only Once</title>
</head>
<body>

Click the 'Back' button <br>
(go on, you know you want to!).

</body>
</html>

Click the Submit button to see this code in action.