View Full Version : Help with cookies?

07-14-2007, 03:41 AM
Consider the following code, which creates, reads, and deletes a cookie that will probably not expire in the users lifetime, unless he tells it to:

//this code will go in a script in the head section
function createCookie(name,value,days) {
if (days) {
var date = new Date();
var expires = "; expires="+date.toGMTString();
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";

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) return c.substring(nameEQ.length,c.length);
return null;

function eraseCookie(name) {

How can I implement it in forms, so that a user can type in his name, and it will apear on multiple pages where I want it to? Also, how can I store images in a cookie(If I can?) If some one can give me a link to a place that teaches me alot of ways to implement cookies like this I would greatly appreciate it.

07-14-2007, 03:47 AM
Try http://w3schools.com/js/js_cookies.asp It helps alot i think

07-14-2007, 03:52 AM
Thnx, I'll check it out.

EDIT: That only tells me how to do what the code above does already. I know how to create and read the cookie, but I want the user to submit information that is turned into a cookie, and other ways of using a cookie set either by the user or me to do different things on a website.

07-14-2007, 04:01 AM
o, all i can think of is to do a google search for it

07-14-2007, 04:06 AM
I looked on google, and found nothing.

Funny, everyone can tell you how to create them, but not to implement them. So I came here hoping for answers. :)

07-14-2007, 08:35 AM
How many users will this be for?

07-14-2007, 09:56 PM
This will be for everyone who uses the page.

07-15-2007, 05:53 AM
Here is a form using a cookie:
<script type="text/javascript">
var cook=document.cookie.split("; ");
var now=new Date();
var exp=new Date(now.getTime()+365*24*60*60*1000);
function getCookie(cookname) {
if (! cook) { return false; }
for (var i=0; i<cook.length; i++) {
if (chip[0] == cookname) {
return unescape(chip[1]);
return "";
function setCookie(cookname, cookval) {
if (cookval != null && cookval != "") {
document.cookie=cookname+"="+escape(cookval)+"; expires="+exp.toGMTString();
cook=document.cookie.split("; ");
function LoadCookie(){

<form name="my_form" method="post" action="" enctype="multipart/form-data">
Name: <input type="text" name="user" value="" size="" maxlength="50" onchange="setCookie('User',this.value)" /><br />
Image: <input type="text" name="txt" value="" size="" maxlength="200" onchange="setCookie('Txt',this.value)" /><br />

07-15-2007, 02:59 PM
Wow, thanks!!!

Anything else that I can do with cookies?