View Full Version : Javascript cookies

08-04-2010, 12:04 PM
Hi all,

I've been trying to set, get and delete js cookies for a while now, although they seem to set (from what I can tell) I can't seem to do what else I need with them.

This is what I'm trying to do:

Function1 - setCookie (sets a cookie called 'saveAndExit' - that's it, no expiry date)

Function2 - useCookie (checks to see if a cookie called 'saveAndExit' exists and if it does alert("COOKIE WORKS") and then deletes the cookie

If it doesn't exist alert("cookie does not exists")

Could anyone assist with this? It's been driving me insane for days!


Philip M
08-04-2010, 12:49 PM
Cookies have been covered very many times in this forum. Have you tried the search feature? It is rather tedious to have to constantly repeat the same scripts/solutions. Here is a basic cookie script:-

<body onload ="readCookie('mycookie'); eraseCookie('mycookie'); createCookie('mycookie','anyvalue', 7)">

<script type = "text/javascript">

function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
var expires = "; expires = "+ date.toGMTString();
else var expires = "";
document.cookie = name + "="+ value + expires + "; path=/"; // available throughout the directory

function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) {;
retval = c.substring(nameEQ.length,c.length);
alert (retval); // for testing
return retval;
return null;

function eraseCookie(name) {
createCookie(name,"",-1); // set cookie to expire on previous day


name = "mycookiename" or whatever name you wish to give the cookie
value = "anything"
days = number of days cookie to remain active (say 7)

It is your responsibility to die() if necessary….. - PHP Manual