PDA

View Full Version : basic help with cookies



axcxe
Dec 10th, 2002, 04:25 AM
Hi, I am a student and I am working on a page that stores the name of a visitor, how many times they have visited, and then resets the experation to one year. So far my code looks like this:
//in the head section
var userName = prompt("What is your name ?");
var cookieCount = 0;
function setCookie() {
var expiresDate = new Date();
expiresDate.setFullYear(expiresDate.getFullYear() + 1);
document.cookie = "username=" + userName;
++cookieCount;
}

alert("Welcome " + userName + " You have visited us " + cookieCount + " times")
My book isn't helping much with what I need to do next. Can someone give me a shove in the right direction?

whammy
Dec 10th, 2002, 06:29 AM
Looks like you're setting the cookie count to 0 no matter what the actual cookie value is...

var cookieCount = 0;

I would read the cookiecount value first and then increment it, depending upon a condition.

I don't see anywhere in the code where you're actually reading a cookie, I'd figure out some way to read the cookie and THEN update the cookieCount value.

shove... ;)

krycek
Dec 10th, 2002, 11:28 AM
I dunno if this will help you or not, but here goes:



//----- COOKIE OBJECT ------------------------------------------------------------------------------------------------------------------//
function CookieObject() {
this.cookie = null
this.cookies = new Array()
}
CookieObject.prototype.save = function(name, value, time) {
this.cookie = name + "=" + value
if (time != null) {
var date = new Date()
date.setTime(date.getTime() + (time * 1000))
this.cookie += "; expires=" + date.toGMTString()
}
this.cookie += "; path=/"
document.cookie = this.cookie
}
CookieObject.prototype.read = function(name) {
name += "="
this.cookies = document.cookie.split(";")
for (var i = 0; i < this.cookies.length; i++) {
this.cookie = this.cookies[i]
while (this.cookie.charAt(0) == " ") {
this.cookie = this.cookie.substring(1, this.cookie.length)
}
if (this.cookie.indexOf(name) == 0) {
return this.cookie.substring(name.length, this.cookie.length)
}
}
return null
}
CookieObject.prototype.clear = function(name) {
this.save(name, "", -1)
}
cookie = new CookieObject()


Those are the cookie functions I use myself :)

::] krycek [::

chrismiceli
Dec 10th, 2002, 03:46 PM
it is always a good idea to excape your cookies, like this


var userName = prompt("What is your name ?");
var cookieCount = 0;
function setCookie() {
var expiresDate = new Date();
expiresDate.setFullYear(expiresDate.getFullYear() + 1);
document.cookie = escape(";username=" + userName + "cookiecount=" + cookieCount);
++cookieCount;
}
cook = unescape(document.cookie)
user&cook = cook.split(";")
user = user&cook[0].split("=");
timesvisited = user&cook[1].split("=");
alert("Welcome " + user[1] + " You have visited us " + timesvisited[1] + " times")