Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Wanet Telecoms Ltd on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem retrieving cookie-data

Status
Not open for further replies.

Peter74

Technical User
Jul 27, 2003
10
DK
Hello,

I'm having som problems with cookies. From a website I found the following two general functions for setting and getting a cookie:

function setCookie(name, value, expires, path, domain, secure) {
var curCookie = name + "=" + escape(value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
document.cookie = curCookie;
}

function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);

if (begin == -1) {

switch (name) {
case 'theme': setCookie("theme","default");break;
case 'sortBy': setCookie("sortBy","title");break;
case 'sortOrder': setCookie("sortOrder","desc");break;
case 'printWithPic': setCookie("printWithPic","no");break;
default: setCookie(name,"");

}
begin = dc.indexOf(prefix);
if (begin != 0) return null;
} else
begin += 2;
var end = document.cookie.indexOf(";", begin);

if (end == -1)
end = dc.length;
return unescape(dc.substring(begin + prefix.length, end));
}

The switch-block was added by me to give "name" a default value in the case no value has been set.

This code works fine in IE, but not in mozilla. If I do this:

var tmp = getCookie("theme");
alert("value is " + getCookie("theme"));

The alertbox in mozilla writes: Value is null

What is wrong with this code?

Notice that I write:

var tmp = getCookie("theme");
alert("value is " + getCookie("theme"));

The reasson I call getCookie twice is that if the value of "name" has not been defined, it needs to be set to some default value. I can then call the function again and get this value. I tried doing this recursively by adding this just after the switch-block:

getCookie(name);

but then mozilla javascript console writes: Too much recursion

How can I do this so that I don't have to call getCookie twice several places in my site?

Thanks
/Peter
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top