Weird Thoughts From Eric's Head

Tags - Categories : All | AJAX | BUSINESS | PERSONAL | PROGRAMMING | BOOK REVIEW

Smack!
Jack came to work Monday and his co-workers asked him how his weekend was. He said he played a little golf. So his co-worker asked him how well he did. "I hit two of my best balls," he said. "Tell me about it," said his co-worker. "I stepped on a rake."

Preventing Multiple Form Submissions
A question that comes up all of the time in the JavaScript forum on JavaRanch is how can I prevent multiple form submissions. Well I am getting tired of answering the question so I thought I would blog about it and point future questions here!

The first choice you have is to use an onclick handler on the submit button to either disable or hide the button.

onclick="this.disabled=true"
onclick="this.visibility='hidden'"
onclick="this.display='none'"


Another method is to use a validation method with the onsubmit handler on the form. This uses a Boolean to determine if the button has been pressed.
<form onsubmit="return Validate()">
<script>
  wasSubmitted=false;
  function Validate(){
    if(!wasSubmitted){
      wasSubmitted=true;
      return true;
    }
    else return false;
  }
</script>
BUT there is a major problem with this since the Boolean is easily over written when the page is refreshed. Submitting the form can also cause it to be overwritten. You can try to use a cookie to hold the value, but you have to rely on cookies being enabled.

Another thing is send the user to a confirmation page that the form has been submitted! The action tag is there for a reason in the form attributes.

The best bet is to use your server side code to determine if there are multiple submissions since JavaScript can be disabled. Your server side code can not!
Use a session variable or IP address of the user and log if the information has been submitted. If it has then you do not process the request. This will eliminate the multiple clicks.

Eric Pascarello
Moderator of HTML/JavaScript at www.JavaRanch.com
Author of: JavaScript: Your Visual Blueprint for Dynamic Web Pages