LebGeeks

A community for technology geeks in Lebanon.

You are not logged in.

#1 March 21 2012

PatrickSaad
Member

Problem with Javascript Cookies

Been trying to use cookies using Javascript. Basically I checked this link on w3schools http://www.w3schools.com/js/js_cookies.asp and tested it on localhost.

It worked fine, I checked the cookies on Chrome and everything is there, but when I move the code to the website, things get messy.

Basically I have a small icon image that's defined in header.php, so basically it's showing on every page of the website, and when the user clicks the image, I want to set a cookie that saves the background color of the website's body. Now when I'm on the homepage and I click it, it does set the cookie and if I refresh the page, it does retrieve it and sets the background color to the newly 'cookied' one.

The problem is when I access another page on the website, say www.mywebsite.com/about and click that small icon, it adds a totally NEW cookie on the website, although both cookies have the same name, the Path seems to change. This doesn't happen on localhost ...

How can I keep updating the same cookie on my entire website without creating a new cookie if the user clicks on the image icon on different pages?

Last edited by PatrickSaad (March 21 2012)

Offline

#2 March 22 2012

elie684
Member

Re: Problem with Javascript Cookies

You can try to set cookie path to root "/"

Offline

#3 March 22 2012

PatrickSaad
Member

Re: Problem with Javascript Cookies

I could swear I tried that before and it didn't work, but it just worked now!

The setCookie code:

function setCookie(c_name,value,exdays)
{
	var exDate=new Date();
	exDate.setDate(exDate.getDate() + exdays);
	var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exDate.toUTCString() + "; path=/");
	document.cookie=c_name + "=" + c_value;
}

Thanks Elie.

Offline

#4 March 22 2012

samer
Admin

Re: Problem with Javascript Cookies

A word of advice, use the Mozilla Developer Network instead of w3schools. The latter is full of outdated material and has nothing to do with the W3C despite their name.

Offline

Board footer