Google Answers Logo
View Question
 
Q: JavaScript: Cookie: Submit Form only once every 3 months ( Answered 5 out of 5 stars,   0 Comments )
Question  
Subject: JavaScript: Cookie: Submit Form only once every 3 months
Category: Computers > Internet
Asked by: cclegg06-ga
List Price: $15.00
Posted: 30 Mar 2003 10:41 PST
Expires: 29 Apr 2003 11:41 PDT
Question ID: 183253
I have a site that loads one of several random forms upon visit.  I
would like to prevent any one visitor (computer) from filling out more
than one form in a given 3 month period.

I suspect this is best done by setting a cookie that expires in 90
days upon loading of a confirmation page (all forms go to the same
destination page after a form is submitted.)  Once this confirmation
page loads, if the visitor tries to go back to the main random form
loading page (either right away or later on), he or she is greeted
with a alternative page that states they can only fill out/ view a
form (any of the forms) once every 3 months.

The script should be called from an external file.  Please provide
both a simple JavaScript external file script and html code.
Answer  
Subject: Re: JavaScript: Cookie: Submit Form only once every 3 months
Answered By: theta-ga on 01 Apr 2003 17:24 PST
Rated:5 out of 5 stars
 
Hi cclegg06-ga,
   I have posted the required code below. Here is an explanation of
how it works. The example HTML file contains checks for the cookie in
two places:
   - once when the page is loaded, in the <body> tag's onLoad event.
If the cookie already exists, the page does not load the form. Instead
it shows a message, asking the user to wait for 90 days.
   - The cookie is also looked for when the form's Submit button is
pressed. If the cookie is not present, a new cookie, set to expire in
90 days, is written, and the form is allowed to be sent. If the cookie
already exists, then the user is shown an error message, and the form
is not sent.

   The Javascript file consists of four functions:
     - CheckForCookie(): This function is the one that is put in the
<body> tag's onload event. It displays a message on the page if the
cookie already exists.
     - CheckForm(): This function is put in the form's onSubmit event.
It allows the form to be submitted if the cookie does not
exist.Otherwise, the user sees an error message, and the form is not
submitted.
     - WriteCookie(): This is the function that actually writes the
cookie. It takes in five arguments, for more information on these is
provided below.
     - ExistsCookie(): This function returns true is the specified
cookie exists, else it returns false.

   The WriteCookie function takes the following 5 arguments:
   - name : name of the cookie.
   - data : the data to be stored in the cookie.
   - expiryDate : Thisis a Javascript Date object specifying the
expiry date for this cookie. Setting no expiration date on a cookie
causes it to expire when the browser closes. If you set an expiration
date in the past, the cookie is deleted.
   - domain : Setting the domain of the cookie allows pages on a
domain made up of more than one server to share cookie information.
   - path : Setting a path for the cookie allows the current document
to share cookie information with other pages within the same
domain—that is, if the path is set to /thispathname, all pages in
/thispathname and all pages in subfolders of /thispathname can access
the same cookie information.
     Only the name and data values are necessary, you can set the rest
to null if you want.

   Whenever you want a page to write a cookie, have it call the
WriteCookie function with suitable values for name, data and
expiryDate. If you want a page to display a message when the cookie is
found, have it call the CheckForCookie() function.

   You can get the relevant source files from:
   [HTML] : www31.brinkster.com/tanm/GA/cookie.htm
   [Javascript]:   www31.brinkster.com/tanm/cookie.js
   Please Note: In the example HTML page, when you click on the Submit
button, the browser will submit the form, and then refresh the page.
When the browser refreshes the page, the CheckForCookie() function in
the <BODY> tag, detects the cookie and displays the 90 days message
instead of the form.

   For your convenience, I have posted the code below:

+++++++++++++++++ Begin HTML+++++++++++++++++++
<html>
<head>
   <script language="javascript" src="cookie.js">
   </script>
</head>
<body onload="CheckForCookie();">
<center>
  <form >
    <input name="submit" type="submit"  onclick="CheckForm();"
value="Submit">
  </form>
</center>
</body>
</html>

++++++++++++++++++ End HTML++++++++++++++++++++


+++++++++++++++ Begin Cookie.js +++++++++++++++

var cname = "FormSubmitted" // name of the cookie
var data ="1";  // data to be stored(should not be null)
var cpath = "";  // path for which allowed [Optional]
var cdomain = "";// domain for which allowed [optional]

// Checks whether the cookie exists or not
// If the cookie exists, it display the specified message on the page
function CheckForCookie()
{
  if( ExistsCookie(cname) )
   {
     document.write("<center><h1>You have already submitted the
form!!</h1>"
	                +"<br> <h3> You cannot submit this form again, until
three months "
					+" (since the day you first submitted it) have elapsed.<br></h3>"
					+"<h4> Thank You for your interest.</h4>"
					+"</center>");
   }
}

// Checks whether the form should be submitted or not
// If the cookie exists, the form is not submitted
// if no cookie exists, a new cookie, set to expire after
// three months ,is written and the form is submitted
function CheckForm()
{
  if( !ExistsCookie(cname) )
  {
    // Write a cookie set to expire after 90 days
      now= new Date();  // get current date and time
      expiry = new Date();
	  expiry.setTime((now.getTime() + 90*24*60*60*1000)); // set to 90
days from now
	  WriteCookie(cname,data,expiry,cpath,cdomain); // Write cookie
	  return true;
  }
  alert("You have already submitted this form");
  return false;
}  

//Writes the specified data to the cookie file
function WriteCookie(name,data,expiryDate,path,domain)
{    
  if( name==null || name=="" || data==null || data=="")
  {
     alert("You must provide both name and data values to write the
cookie.");
	 return false;
  }
  
  var Cookie = name + "=" + escape(data)
               + ( (expiryDate)? "; expires=" +
expiryDate.toGMTString() : "" );
               + ((path)? "; path=" + path : "" )
               + ((domain)?"; domain=" + domain : "" );
	  Cookie +=";";
	//Set cookie
   document.cookie = Cookie;
   return true;
}

//Checks if the specified cookie exists or not
function ExistsCookie(name)
 {
  // cookies are separated by semicolons
  var aCookie = document.cookie.split("; ");
  for (var i=0; i < aCookie.length; i++)
  {
    // a name/value pair is separated by an equal sign
    var aCrumb = aCookie[i].split("=");
    if (name == aCrumb[0]) 
      return true;
  }

  // a cookie with the requested name does not exist
  return false;
}

+++++++++++++++ End Coookie.js ++++++++++++++++
Be careful if you intend to copy and paste the above code. Due to the
way in which Google Answers formats all postings, very long lines of
code will get pushed onto the next line, resulting in syntax errors
when you try to run the code. I recommend that you download the
relevant files using the links provided above.

Hope this helps.
If you need any clarifications, or modifications to the code, just
ask!

Regards,
Theta-ga
:-)

Request for Answer Clarification by cclegg06-ga on 01 Apr 2003 19:36 PST
Thank you.  I'll work on implementing the solution this weekend if not
sooner and get back to you with any quesitons.

I can't seem to get access to the cookie.js file you suggested I
access via the link provided.  Can you double check the link?

Thanks.

Clarification of Answer by theta-ga on 01 Apr 2003 22:44 PST
Hi cclegg06-ga,
   WHOOPS!! My bad. The link for the cookie file is missing the
directory in which it resides. Here is the updated, successfully
tested, fully working(honest!) link:
      http://www31.brinkster.com/tanm/GA/cookie.js

   Sorry for the inconvenience. Blame it on the lack of sleep. :-P
Regards,
Theta-ga
:-)

Request for Answer Clarification by cclegg06-ga on 02 Apr 2003 07:19 PST
I tried the link again and now It just seems to hang up during the
file down load process, never getting past the "getting file
information" stage.

(Note this has happened before when trying to access links for other
answers you've provided me.  It's never really been an issue becuas I
could copy and past the code without worry.)

Any suggestions?

Clarification of Answer by theta-ga on 02 Apr 2003 13:38 PST
Hi cclegg06-ga, 
   I have reformatted the cookie.js file, so (hopefully) GA should no
longer have any problems with it. Try copying and pasting the code
below.

+++++++++++++++ Begin Cookie.js +++++++++++++++ 

var cname = "FormSubmitted" // name of the cookie
var data ="1";    // data to be stored(should not be null)
var cpath = "";   // path for which allowed [Optional]
var cdomain = ""; // domain for which allowed [Optional]


// Checks whether the cookie exists or not
// If it exists, it display a specified message on the page
function CheckForCookie()
{
  if( ExistsCookie(cname) ) // If the cookie is found
   {
     // Show message 
     document.write("<html><head><title>"
       +"The Form has already been submitted!!</title>"
       +"</head><body><center>"
       +"<h1>You have already submitted the form!!</h1><br><h3>"
       +"You cannot submit this form again, until three months "
       +"(since the day you first submitted it) have elapsed."
       +"</h3><br><h4> Thank You for your interest.</h4>"
       +"</center></body></html>");
   }
}



// Checks whether the form should be submitted or not
// If the cookie exists, the form is not submitted
// if no cookie exists, a new cookie, set to expire after
// three months ,is written and the form is submitted
function CheckForm()
{
  if( !ExistsCookie(cname) )
  {
    // Write a cookie set to expire after 90 days
    now= new Date();  // get current date and time
    expiry = new Date();
    // Set expiry Date to 90 days from now
    expiry.setTime((now.getTime() + 90*24*60*60*1000));
    
    WriteCookie(cname,data,expiry,cpath,cdomain); 
    
    return true;
  }
  
  // The user has already clicked submit once
  alert("You have already submitted this form");
  return false;
}  




// Writes the specified data to the cookie file
function WriteCookie(name,data,expiryDate,path,domain)
{  
  // The name and data arguments are compulsory  
  if( name==null || name=="" || data==null || data=="")
  {
     alert("You must provide both name & data values.");
     return false;
  }
  
  var Cookie = name + "=" + escape(data)
        +((expiryDate)?"; expires="+expiryDate.toGMTString():"")
        + ((path)? "; path=" + path : "" )
        + ((domain)?"; domain=" + domain : "" );
         
   //Set cookie
   document.cookie = Cookie;
   return true;
}



//Checks if the specified cookie exists or not
function ExistsCookie(name)
 {
  // cookies are separated by semicolons
  var aCookie = document.cookie.split("; ");
  for (var i=0; i < aCookie.length; i++)
  {
    // a name/value pair is separated by an = sign
    var aCrumb = aCookie[i].split("=");
    if (name == aCrumb[0]) 
      return true;
  }

  // a cookie with the requested name does not exist
  return false;
}

+++++++++++++++ End Coookie.js ++++++++++++++++ 

Hope this helps.

Regards,
Theta-ga
:-)

Request for Answer Clarification by cclegg06-ga on 04 Apr 2003 18:16 PST
Thank you for this.  I’ve been struggling with the implementation for
a bit and I’m sure it has nothing to do with your code.

I now have three functions running on the page (all suggested by
yourself – thanks):

-	Only allowing one submit
-	 A form timer
-	the cookie to prevent repeat visitors (90 days)

I’m calling them with:

   <input type="submit" value="Click once to submit your response" 
                     name="submit" 
                     onSubmit="checkForm();"
                     onClick=submitForm(); StopTimer();"
                     style="font-size: 10pt; font-family: Verdana">

The problem is that they are not all coming together.  By themselves
the submit form and stoptimer work fine.  When I bring them together,
the timer works but the submit form is not reliable.

The whole thing seems to go broke when I try to add the cookie.

Can you look back on the past 3 codes you’ve provided and help me with
the merging of all three…?  (I’ve added/ will add $15 to the overall
question fee).

If you’d prefer not to… that’s fine.  I’ll close this answer out and
post a new one related to the merging of the three functions.

Thanks

Request for Answer Clarification by cclegg06-ga on 04 Apr 2003 18:22 PST
If it's possible, I'd like to do it all from the same JS file.

Thanks.

Clarification of Answer by theta-ga on 04 Apr 2003 21:30 PST
Hi cclegg06-ga,
   Absolutely no problems, I will take a look at it.
Regards,
Theta-ga
:-)

Clarification of Answer by theta-ga on 05 Apr 2003 23:56 PST
Hi cclegg06-ga,
   Here is an implementation of the unified javascript file which
brings together the functionality asked for in your previous three
questions. A couple of functions have been dropped, to be replaced by
the new SubmitForm() function. Minor changes have been made to some of
the other functions.

Here is a list of fuctions contained in the file:
- SubmitForm(): This function is called when the user clicks the
Submit button on the form. If the form has been filled in correctly,
and the user has not submitted this form before, it writes acookie to
the disk and allows the form to be submitted.

- VerifyForm(): This is called by the SubmitForm() fn to verify the
the form has been filled in correctly. Currently this function is
empty. You should replace it with code for checking and verifying the
form contents.

- Startimer(), StopTimer(), ResetTimer(): The same as defined in my
answer to one of your previous questions.

- CheckForCookie(),WriteCookie(), ExistsCookie(): The same as defined
in my answer above.

Here is a guide to calling these functions on your form page:
[ HTML Tag ]             [ Event ]        [ Function Name]
<BODY>                    OnLoad           CheckForCookie()
<INPUT type="SUBMIT"      OnClick          SubmitForm()
<INPUT type="RESET"       OnClick          StopTimer()
Other Form Elements       OnFocus          StartTimer()

Please note: In some places, the code refers to certain form
elements(the hidden field, submit button) by name. Since the name you
use for your form elements will vary from what I use in my example,
you will have to change these lines before you can use this javascript
with your forms. The lines that have to be changed have been marked
with the following comment "//CHANGE".

You can get the sample HTML file and the Javascript code from:
[Html] ( http://www31.brinkster.com/tanm/GA/subOnce.htm )
[JS]   ( http://www31.brinkster.com/tanm/GA/subOnce.js )

For your convenience, I have included the contents of the javascript
file (all 160 lines!!) below.
================== BEGIN subOnce.htm ======================

<html>
<head>
   <script language="javascript" src="subOnce.js"></script>
</head>
<body onLoad="CheckForCookie();">
   <FORM NAME="myForm" >
      <PRE>
      Button        <INPUT TYPE="BUTTON" VALUE="Button"
onfocus="StartTimer();" >
      CheckBox      <INPUT TYPE="CheckBox"  onfocus="StartTimer();">
      File          <INPUT TYPE="FILE"  onfocus="StartTimer();" >
      Hidden        <INPUT TYPE="HIDDEN" name="myhiddenfield"
VALUE="0" >
      Password      <INPUT TYPE="PASSWORD" NAME="myPass
onfocus="FormClicked();" onchange="StartTimer();" >
      Radio         <INPUT TYPE="RADIO" NAME="myRadio" value="Radio"
onfocus="StartTimer();" >
      Text          <INPUT TYPE="TEXT" NAME="myText" 
onfocus="StartTimer();" >
      Textarea      <TEXTAREA NAME="myTextarea" 
onfocus="StartTimer();" ></TEXTAREA>
      Select object <SELECT NAME="mySelect"  onfocus="StartTimer();"
><OPTION>1<OPTION>2<OPTION>3</SELECT>

      Reset object  <INPUT TYPE="RESET"  onfocus="ResetTimer();" >
      Submit object <INPUT TYPE="SUBMIT" name="mysubmitbutton"
onclick="SubmitForm();" >
      </PRE>
   </FORM>
</body>
</html>

================== END subOnce.htm ========================


================== BEGIN subOnce.js =======================

var formSubmitted = false;

var timerStarted=false;
var startTime=0, stopTime=0, timeTaken=0;

var cname = "FormSubmitted" // name of the cookie 
var data ="1";    // data to be stored(should not be null) 
var cpath = "";   // path for which allowed [Optional] 
var cdomain = ""; // domain for which allowed [Optional] 


function SubmitForm()
{
  //check if the form has been submitted before
  if( formSubmitted || ExistsCookie(cname) )
  {
     alert("You have already submitted this form!");
     formSubmitted = true;
     document.myForm.mysubmitbutton.disabled=true; //CHANGE
     return false;
  }
  
  // Form has not been submitted before
  //Check if it was filled completely
  if( verifyForm() == false )
  {
    alert ("Please complete the form before you submit it.");
    return false; // Don't submit
  }
  // The form has been filled in completely. Submit it

    StopTimer();  // Set the time value in the hidden field  
    formSubmitted = true;    // Set the formSubmitted flag

    // Write a cookie set to expire after 90 days 
    now= new Date();  // get current date and time 
    expiry = new Date(); 
    // Set expiry Date to 90 days from now 
    expiry.setTime((now.getTime() + 90*24*60*60*1000)); 
     
    WriteCookie(cname,data,expiry,cpath,cdomain);  
    // Show message to the user
  alert("Submitting Form....\nThank you!"); 
  return true;
}


function verifyForm()
{

  // Use this function to ensure that all the
  // required data has been entered in the form

  // return true if the form is complete
  // return false if its not

  return true;
}


function StartTimer()
{
  if( !timerStarted)
  {  
     startTime = new Date();
     startTime=startTime.getTime();// get time in milliseconds
     timerStarted = true; //Timer Enabled
  }
}


function StopTimer()
{
  if( startTime ==0 || formSubmitted )
   {
     // Change myForm to your Form name
     // Change myhiddenfield to your hiddenfield name
     window.document.myForm.myhiddenfield.value=0; //CHANGE
   }
  else
   {
     stopTime = new Date();
     stopTime=stopTime.getTime();
     timeTaken = (stopTime - startTime)/(1000);

     // Change myform to Your Form name
     // Change myhiddenfield to your hiddenfield name
     document.myForm.myhiddenfield.value= timeTaken; //CHANGE
   }
  
   //Reset the Timer
   ResetTimer();
}


function ResetTimer()
{
  //Reset Timer Info
  startTime=0;
  timerStarted=false; // Disable Timer
}


// Checks whether the cookie exists or not 
// If it exists, it display a specified message on the page 
function CheckForCookie() 
{ 
  if( ExistsCookie(cname) || formSubmitted )  
   { 
     // Show message [ Change this message to suit your needs ] 
     document.write("<html><head><title>" 
       +"The Form has already been submitted!!</title>" 
       +"</head><body><center>" 
       +"<h1>You have already submitted the form!!</h1><br><h3>" 
       +"You cannot submit this form again, until three months " 
       +"(since the day you first submitted it) have elapsed." 
       +"</h3><br><h4> Thank You for your interest.</h4>" 
       +"</center></body></html>"); 
   } 
} 
 

// Writes the specified data to the cookie file 
function WriteCookie(name,data,expiryDate,path,domain) 
{   
  // The name and data arguments are compulsory   
  if( name==null || name=="" || data==null || data=="") 
  { 
     alert("You must provide both name & data values."); 
     return false; 
  } 
   
  var Cookie = name + "=" + escape(data) 
        +((expiryDate)?"; expires="+expiryDate.toGMTString():"") 
        + ((path)? "; path=" + path : "" ) 
        + ((domain)?"; domain=" + domain : "" ); 
          
   //Set cookie 
   document.cookie = Cookie; 
   return true; 
} 
 
 
//Checks if the specified cookie exists or not 
function ExistsCookie(name) 
 { 
  // cookies are separated by semicolons 
  var aCookie = document.cookie.split("; "); 
  for (var i=0; i < aCookie.length; i++) 
  { 
    // a name/value pair is separated by an = sign 
    var aCrumb = aCookie[i].split("="); 
    if (name == aCrumb[0])  
      return true; 
  } 
 
  // a cookie with the requested name does not exist 
  return false; 
} 

================== BEGIN subOnce.js =======================

Hope this helps.
If you need any clarifications, just ask!

Regards,
Theta-ga
:-)
cclegg06-ga rated this answer:5 out of 5 stars and gave an additional tip of: $25.00
To: theta-ga

Thank you.  All three scripts are fully implemented and working better
than I could have expected.  Many thanks for your patience,
persistence, and talent.

I look forward to working with you again in the future.

To: Anyone Else

“theta-ga” is an absolute pleasure to work with.  His/ her total
professionalism combined with a mastery of JavaScript has far exceeded
my expectations on several occasions.

Comments  
There are no comments at this time.

Important Disclaimer: Answers and comments provided on Google Answers are general information, and are not intended to substitute for informed professional medical, psychiatric, psychological, tax, legal, investment, accounting, or other professional advice. Google does not endorse, and expressly disclaims liability for any product, manufacturer, distributor, service or service provider mentioned or any opinion expressed in answers or comments. Please read carefully the Google Answers Terms of Service.

If you feel that you have found inappropriate content, please let us know by emailing us at answers-support@google.com with the question ID listed above. Thank you.
Search Google Answers for
Google Answers  


Google Home - Answers FAQ - Terms of Service - Privacy Policy