Problems with Cookie Script

They have: 9 posts

Joined: May 2002

Hi, all...

I'm attempting to utilize a cookie script that leaves a basic cookie on a visitors' machine without any knowledge of the user. All of the scripts I have found seem to use those annoying alerts or details in the HTML how many times a user has visited, etc.

If anyone knows of any cookie javascripts that would set a cookie the way I need, I'd very much appreciate it.

Cheers,

Fredman

Jack Michaelson's picture

He has: 1,733 posts

Joined: Dec 1999

This helped me setting cookies:
http://www.htmlgoodies.com/beyond/cookie.html

Hope it helps,

They have: 9 posts

Joined: May 2002

Thanks, Jack!

Unfortunately the code on that page includes a form so the user actually activates the cookie. WhatI need to do is set the cookie without the user having to see or do anything. Is there a way of taking out the code that uses the prompts to achieve this?

Cheers Wink

Fred

Peter J. Boettcher's picture

They have: 812 posts

Joined: Feb 2000

Just add the following to the body tag:

Onload="putCookie();"

then in the function replace this line:

YouEntered=document.cf.cfd.value;

with your variable, for example:

var MyVariable = 'test';

YouEntered=MyVariable;

That should do it.

PJ | Are we there yet?
pjboettcher.com

They have: 9 posts

Joined: May 2002

Thanks, Peter!

I'm a newbie when it comes to coding cookies. If you'd have an example code I could play with or use, I'd be forever in your debt!

Cheers,

Fred

Peter J. Boettcher's picture

They have: 812 posts

Joined: Feb 2000

Here's a couple quick functions for setting and retrieving a cookie value:

function setcookie(name,value) {
var today = new Date();
var expires = new Date();
expires.setTime(today.getTime() + 60*60*24*365);
document.cookie = name + "=" + escape(value) + ((expires == null) ? "" :
("; expires=" + expires.toGMTString()));
}

function getcookie(name,dfault) {
var search = name + "=";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search);
if (offset != -1) {
offset += search.length;
end = document.cookie.indexOf(";", offset);
if (end == -1) {
end = document.cookie.length;
}
return unescape(document.cookie.substring(offset,end));
} else { return dfault;
}
} else { return dfault;
}
}

So, to set the cookie value you would call setcookie("KeyName","Value"), and to retrieve it again, getcookie("KeyName")

PJ | Are we there yet?
pjboettcher.com

They have: 9 posts

Joined: May 2002

Most excellent!

Thank you!

Fred

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.