Cookie question

J

Jim Davidson

I learning JavaScript and doing something wrong here, what I want to
do is store the contents of a variable to a cookie so that it would
show the next time the page was opened. I'm doing something wrong in
the code below because instead of saving the value of nLastBonus to
the cookie I'm saving "nLastBonus".

Can someone point me in the right direction?

// Get the cookie
var nLastBonus = get_cookie()

// Did the cookie exist?
if (nLastBonus) {

// If not, then store 100 to nLastBonus
// visit_number = 1
nLastBonus = 100
}
else {

// Otherwise, increment nLastBonus
nLastBonus++
}

// Set the cookie
document.cookie="last_bonus=nLastBonus; expires=" + expire_string
 
L

Lasse Reichstein Nielsen

I'm doing something wrong in the code below because instead of
saving the value of nLastBonus to the cookie I'm saving
"nLastBonus".

I assume the rest works. Change:
document.cookie="last_bonus=nLastBonus; expires=" + expire_string
to
document.cookie="last_bonus="+escape(nLastBonus)"+; expires="+expire_string;

Generally, you should escape the values stored in cookies to make sure
they don't contain meaningfull characters. In this case, it isn't
necessary, since numbers are safe, but if nLastBonus was the string
"foo;expires=now;" (or something similar that works) then you will get
trouble.

/L
 
J

Janwillem Borleffs

Lasse Reichstein Nielsen said:
document.cookie="last_bonus="+escape(nLastBonus)"+; expires="+expire_string;

And when you get an error on the above line, change it into:

document.cookie="last_bonus="+escape(nLastBonus)+"; expires="+expire_string;


JW
 
J

Jim Davidson

Janwillem Borleffs said:
And when you get an error on the above line, change it into:

document.cookie="last_bonus="+escape(nLastBonus)+"; expires="+expire_string;


JW


Thanks guys that worked!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top