2

I am trying to implement cookies on a webpage. I am having trouble getting it to function properly. I am wanting to store the value of some variables as well. I realize this is very broad, but I know little to nothing about JavaScript cookies and I am working off the w3schools examples. This is what I have so far:

var days=365;
function setCookie(child,user,days) {
var exdate=new Date();
exdate.setDate(exdate.getDate() + days);
var child=escape(user) + ((365==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=child + "=" + child;
}

function getCookie(child) {
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++) {
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==child) {
    return unescape(y);
    }
  }
}

function checkCookie() {
var username=getCookie("username");
  if (username!=null && username!="") {
  alert("Welcome again " + username);
  } else {
  username=prompt("Please enter your name:","");
  if (username!=null && username!="") {
    setCookie("username",username,days);
    }
  }
}
karel
  • 5,489
  • 46
  • 45
  • 50
HarryJEST
  • 97
  • 3
  • 9
  • What's the functional requirement? "I am trying to implement cookies" gives really nothing to steer you in the right direction. – BalusC Apr 12 '11 at 03:57
  • 3
    One of your parameters is "365". This is not a legal JavaScript identifier and is probably causing some problems. – Matt Greer Apr 12 '11 at 04:05
  • @BalusC: I want it to track the users that visit the page by having them enter their names in a prompt box, and then store their 'score' which is already held in an incrementing variable (I'm guessing I just need a 'var' in the cookie to hold the 'var' that holds the users 'score'. ... if that makes any sense at all – HarryJEST Apr 12 '11 at 04:08

1 Answers1

2

Yes, you have a parse error on line 1. As Matt said, "365" is not legal here.

Also, it looks like this code will never evaluate to true...

if (x==child)
    {
    return unescape(y);
    }
  }

...and so the cookie value y will never be returned.

There are other things that look problematic in your code too, but I would start with what I've mentioned here. Also, try debugging with some JavaScript tools, ie. Firebug.

sonicwizard
  • 165
  • 6
  • Also, style is not subjective in JavaScript. Opening braces should go at the end of lines, not on new lines. What you've written is ok in other languages (c, Java), but not in JavaScript. You'll run into problem due to semicolon insertion. See http://encosia.com/2011/03/21/in-javascript-curly-brace-placement-matters-an-example/ – sonicwizard Apr 12 '11 at 04:43