We help IT Professionals succeed at work.

javascript cookie

merlin2395
merlin2395 asked
on
478 Views
Last Modified: 2008-04-24
I have the following code. I need to modify it so that a cookie is set on the user's computer that will prevent the user from coming back in filling the form again. Preferably I would like the user to be redirected to a page that informs him/her that they have already filled out the form. An alert message may be ok too. The cookie should expire in a month. Any help would be appreciated as I haam running out of time. Thanks in advance


<html>
<head>
<!--  Web410 Individual Assignment
        Author: Gabriel Zamfir
         Date: 05/20/2007
-->
 <title>Kudler Foods Mailing List</title>
</head>

<script language="JavaScript">

function resetform() {
document.forms[0].elements[1]=="";
}
function submitForms() {
if (isName() && isAddress() && isCity() && isState() && isZip() && isEmail() && isTelephone())
if (confirm("\n You will now join our mailing list."))
{
alert("\n Thank you for joining our mailing list!");
return true;
}
else
{
alert("\n You have chosen to abort the submission.");
return false
}
else
return false;
}

function isName() {
if (document.forms[0].elements[1].value == "")
{
alert ("\n Please enter your name!!!")
document.forms[0].elements[1].focus();
return false;
}
return true;
}
function isAddress() {
if (document.forms[0].elements[2].value == "") {
alert ("\n Please enter your address!!!")
document.forms[0].elements[2].focus();
return false;
}
return true;
}
function isCity()
{
if (document.forms[0].elements[3].value == "")
{
alert ("\n Please enter your city!!!")
document.forms[0].elements[3].focus();
return false;
}
return true;
}
function isState() {
if (document.forms[0].elements[4].value == "") {
alert ("\n Please enter your state!!!")
document.forms[0].elements[4].focus();
return false;
}
return true;
}
function isZip() {
if (document.forms[0].elements[5].value == "") {
alert ("\n Please enter your Zip code!!!")
document.forms[0].elements[5].focus();
return false;
}
return true;
}
function isEmail() {
if (document.forms[0].elements[6].value == "") {
alert ("\n The E-Mail field is blank. \n\n Please enter your E-Mail address.")
document.forms[0].elements[6].focus();
return false;
}
if (document.forms[0].elements[6].value.indexOf ('@',0) == -1 ||
document.forms[0].elements[6].value.indexOf ('.',0) == -1) {
alert ("\n Please re-enter your E-Mail address in correct form!!!")
document.forms[0].elements[6].select();
document.forms[0].elements[6].focus();
return false;
}
return true;
}
function isTelephone() {
if (document.forms[0].elements[7].value == "") {
alert ("\n Please enter your telephone number!!!")
document.forms[0].elements[7].focus();
return false;
}
return true;
}
</script>

<body>
<h2><p align=center>Mailing List Form</p></h2>

<form enctype="text/plain" name="addform" method='get'
 action= "Confirmation.html" onSubmit="return submitForms()">

<input type="hidden" name="Form" value="Submit Sub">

<table border=10 bordercolor=black cellpadding=3 cellspacing=0 style=background-color:#ffaaff width=85% align=center>
<tr style=backgroundcolor:white align=center>
<td align=top>
<h4>Sign up here</h4>


<p>Name<br/>
<input type=text name="Name" size=50 /></p>

<p>Address<br/>
<input type=text name="Address" size=50 /></p>

<p>City, State, Zip<br/>
<input type=text name="City" size=33/>
<input type=text name="State" size=2 maxlength=2/>
<input type=text name="Zip" size=5 maxlength=5 /></p>

<p>E-mail address<br/>
<input type=text name="Email" size=50/></p>

<p>Telephone Number<br />
<input type=text name="Telephone" size=50/></p>

<input type="submit"  value= "Submit Request" >

<input type="reset" value="Reset Form" onclick=resetform()>
</input>

<h3><a href= "Kudler Main Page.mht">Return to Main Page</a></h3>


</td>
</tr>
</table>
</form>
</body>
</html>


Comment
Watch Question

b0lsc0ttIT Manager
CERTIFIED EXPERT

Commented:
Is this just an html page or do you use a server language (i.e. ASP, PHP, Perl)?  If this page is already a "server" page then I would use that language to make the cookie and not javascript.  Javascript can make cookies but it is usually easier to make and use cookies in a server language.  Let me know what language if you do want to use a server language or if you want to still use javascript then I can provide script to use.

Let me know if you have a question or need more information.

bol

Author

Commented:
I need the javascript ...thanks

Author

Commented:
I have seen similar code on this website, but for some reason my cookie does not get set.
b0lsc0ttIT Manager
CERTIFIED EXPERT

Commented:
>> I have seen similar code on this website, but for some reason my cookie does not get set. <<

The problem may be the browser.  Post the code you tried to use if you want to test this.  I suggest testing your code on different machines and using different browsers (i.e. IE, Firefox, etc).

The page below is one I have used in the past to show Javascript cookie code ...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
<head>
<link href="style.css" rel="stylesheet" type="text/css" />
<title>JS Cookies</title>

<script type="text/javascript">
<!--
function createCookie(name,value,days) {
      if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            var expires = "; expires="+date.toGMTString();
      }
      else var expires = "";
      document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
      var nameEQ = name + "=";
      var ca = document.cookie.split(';');
      for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
      }
      return null;
}

function eraseCookie(name) {
      createCookie(name,"",-1);
}
//-->
</script>
</head>

<body onload="testCookie();">
<h3>JS Cookies</h3>

<script type="text/javascript">
function testCookie() {
      createCookie('first','one',0);
      //alert("Cookie made");
      var x = readCookie("first");
      if (x) alert(x);
}
</script>
<br /><br />
<a href="js_cookie.htm">Link</a>
</body>
</html>

If you want to try using that code then try it as is and let me know the results.  It can be modified to make a cookie that will expire in a month, etc and I can help with that if needed.

Let me know if you have a question.

bol
b0lsc0ttIT Manager
CERTIFIED EXPERT

Commented:
Since you had a problem with another script then do you have software that provides cookie blocking or privacy?  What browser are you using?  Are you testing the page as a local file or as a web page on a website?  These types of things could cause good script to not work and even to not show an error.

bol

Author

Commented:
no problem with browser. I have used similar code, that is not mine at all and it worked fine. The problem is with sometghing I wrote in the code....don't know what but it is not the browser.
b0lsc0ttIT Manager
CERTIFIED EXPERT

Commented:
Let me know how the code I provided works.  Was the similar code tested on the same site/server?  Check the browser source to make sure the script is up to date and correct.  A cache version can make it appear that the script doesn't work when the script is actually good.

bol

Author

Commented:
I figured out the answer myslef. I had some extra code that was killing my cookie. I had to re do itbut I got done.

Author

Commented:
besides i didn't want code for a generic cookie. I can find that in a billion places. I just wanted to figure ou why it wasn't wqorking in my script.
b0lsc0ttIT Manager
CERTIFIED EXPERT

Commented:
Was the extra code in part of the script you posted above?  If so, post the details of the correction and you can get a moderator to close this and refund your points.  I'm sorry if you thought I was pushing a "generic cookie" code on you but that wasn't my intention.  It was offered just as a step in troubleshooting.  If one of my comments did help you figure this out then please accept it to close this question.  Otherwise feel free to let me know how you would like to see it closed or post a message in General Community Support to let the moderators know.  Let me know if you have a question about any of this.

bol

Author

Commented:
thsi is part of the program with the working cookie. the problem was in the wy I was trying to set the cookie

        function setCookie() {
            var expiresDate = new Date();
            expiresDate.setDate(expiresDate.getDate() + 7);
            document.cookie = encodeURI("name_shipping=" + document.forms[0].name_shipping.value) + "; expires="
     + expiresDate.toUTCString();
         }
         function getUserPrefs() {
     var userPrefs = decodeURI(document.cookie);
     var prefs = userPrefs.split("; ");
     var userName = prefs[0].split("=");
       if(userName[1]){
       mypopup=window.open('PreventResubmit.html','mypopup');

   
<input type="submit" value="Submit" onclick="setCookie();">
<input type="reset" value="Reset Form" onclick="resetform();">
</input>















b0lsc0ttIT Manager
CERTIFIED EXPERT

Commented:
Did you post that comment to provide details of the solution?  If so do you have questions about how to get a moderator to help you close this?  Let me know if you need help or have a question about doing this.

If that is for a question then please explain.

bol

Author

Commented:
I am allset but I am no sure how do I get a moderator to close the question. Thanks
b0lsc0ttIT Manager
CERTIFIED EXPERT

Commented:
Post a message in General Community Support (https://www.experts-exchange.com/Community_Support/General/).  You can use the link in the last sentence and then press the Ask a New Question button.  No points are needed for that message.  Use a title like "Please help close question."  In the body of the question make sure you include the URL of this question when you describe the help you need (i.e. "Please PAQ and refund points.  I solved it myself.").  The moderators there are good about responding and will be able to help with this.

Let me know if you have a question about this.

bol
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.