Click to See Complete Forum and Search --> : reading a cookie


bart m
08-12-2003, 05:29 AM
I have created a function that writes a cookie with certain variables in it:

---

function writeData(name, allpicsSize, numberofPictures)
{

parent.document.cookie="name=" + escape(name) + "; allpicsSize=" + escape(allpicsSize) + "; numberofPictures=" + escape(numberofPictures)
location.href="files/pictures_character_overview.html"
}

---

as you can see, after the cookie is written, another page is loaded. On that page there's another function to read the cookie and assign the values to the right variables:

---

var name=readCookie("name")
var allpicsSize=readCookie("allpicsSize")
var numberofPictures=readCookie("numberofPictures")

function readCookie(required)
{
cookie=unescape(parent.document.cookie)
list=cookie.split(';')
data=""

for (counter=0; counter<list.length; counter++)
{
parts=list[counter].split('=')
if (parts[0].substring(0,1)==' ')
{
parts[0]=parts[0].substring(1,parts[0].length)
}
if (parts[0]==required)
{
data=parts[1]
break
}
}
return data
}

---

But when the page is loaded I find that only the first variable (name) has been given the right value. The other two have no value whatsoever.

Can anyone tell me what I did wrong?

Fang
08-12-2003, 09:05 AM
You have to write 3 seperate cokkies or a string of values.

// 3 cookies:
parent.document.cookie="name=" + escape(name);
parent.document.cookie="allpicsSize=" + escape(allpicsSize);
parent.document.cookie="numberofPictures=" + escape(numberofPictures);
// string comma delimiter, NOT a semicolon
parent.document.cookie="MyCookies="+escape(name)+","+escape(allpicsSize)+","+escape(numberofPictures);

If you use the second approach:

var name="";
var allpicsSize="";
var numberofPictures="";
//Split cookie
var cookieList=document.cookie.split("=");
var crumb=cookieList[1].split(",")
name=crumb[0];
allpicsSize=crumb[1];
numberofPictures=crumb[2];
//Show cookie
alert("name="+name+", allpicsSize="+allpicsSize+", numberofPictures="+numberofPictures)

bart m
08-12-2003, 09:29 AM
Well, this accually DOES seem to work :D! Thanks a lot!

But I don't suppose you can easily see what's wrong with my old code? Because I always try to learn from my mistakes:)

Fang
08-12-2003, 10:29 AM
cookie format:
name=value; [expires=date; [path=path; [domain=domain [secure;]]]]
Your first cookie was set, but the other two were seen as an expiry date and the path.

bart m
08-12-2003, 11:17 AM
Oke, thanks.