Forum Moderators: open

Message Too Old, No Replies

How do I simply display the value of a cookie?

Here is the PHP, how do I do it in JS?

         

JAB Creations

7:05 am on Jun 10, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The JS forum gets very slow responses...

Here is EXACTLY what I want in JS but only this is the PHP version...

echo $HTTP_COOKIE_VARS[cookie_name_here]

This says, get the cookie "cookie_name_here" and print it's value.

If our cookie is named "coffee" and it's value is "black" then if this is the only code on the page, ALL I want it to do is to say "black" on the page.

mcibor

7:19 am on Jun 10, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



These are the functions to deal with cookie:

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

function getCookie(name) {
var varCookie = document.cookie;
var prefix = name + "=";
var begin = varCookie.indexOf(prefix);
if (begin == -1)
return null;
var end = varCookie.indexOf(";", begin);
if (end == -1)
end = varCookie.length;
return unescape(varCookie.substring(begin + prefix.length, end));
}

function deleteCookie(name, path, domain) {
if (getCookie(name)) {
document.cookie = name + "=" +
((path)? "; path=" + path : "") +
((domain)? "; domain=" + domain : "") +
"; expires=Thu, 01-Jan-70 00:00:01 GMT";
}
}

function fixDate(date) {
var base = new Date(0);
var delay = base.getTime();
if (delay > 0)
date.setTime(date.getTime() - delay);
}

I always got my answer on js forum on time:). But here it is truly faster!
Michal Cibor

PS to answer properly your question:

document.write(getCookie("coffee"));

or sth like this. I'm never good with writing raw to document

MattAU

7:40 am on Jun 10, 2005 (gmt 0)

10+ Year Member



I could be wrong, but I don't think there's a simple way of doing it... This should work for basic stuff (not tested though):

var data = document.cookie;
data = document.cookie.split(";");
for(i = 0; i < data.length; i++)
{
key = data[i].split("=");
if(key[0] == 'coffee')
{
document.write(key[1]);
}
}

Hope this helps, I'm pretty green when it comes to javascript :)