Preventing Repeated Form Submissions


<form action="delay.php">   <input type="submit" value="Submit data"     onclick="this.disabled = true;"/> </form> 

Especially when the script that analyzes form data takes quite some time, users tend to try to speed things up by submitting the form again. However, during online shopping, credit-card payments, and other important transactions, this can be quite expensive. Therefore, the web page itself should try to avoid repeated form submissions.

The preceding code (in the file prevent.html in the code downloads for this title) does exactly that: When the submit button has been clicked, the button's disabled property is set to TRue, effectively making it impossible to click the button again (if JavaScript is enabled). Figure 8.5 shows the result in the browser: The button grays out.

Figure 8.5. The button cannot be clicked twice.


The preceding listing and the following listing both send the form data to a PHP script called delay.php, which basically waits five seconds and then sends out data. This emulates a slow connection or a slow server, the main scenario for this phrase.

Another approach is to maintain the state of the button and thereby determine whether it has already been clicked, as the following listing shows:

Preventing a Repeated Form Submission Maintaining a Status (prevent-status.html)

<script language="JavaScript"   type="text/javascript"> var submitted = false; function checkform(f) {   if (submitted) {     window.alert("Form has already been submitted!");     return false;   } else {     submitted = true;     return true;   } } </script> <form action="delay.php"   onsubmit="return checkform(this);">   <input type="submit" value="Submit data" /> </form> 

Warning

Although this phrase is quite convenient, you have to be aware that sometimes the server unexpectedly closes the connection to the client (or vice versa). Then the data transfer stops, but the JavaScript code cannot know about this. The consequence is that the button cannot be clicked twice (as originally planned), but the data has not been properly transmitted. The user then would have to reload the form to be able to submit the data again.





JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net