Use these to jump around or read it all…
[Why Set Cookies?] [My Cookie Script In Action]
[Setting the Cookie] [What’s It Look Like?]
[Retrieve the Cookie] [More Than One Cookie]
This tutorial was really a long time coming. People have wanted it for a while, but I’ve been somewhat reluctant to write it for a couple of reasons.
First, I knew that as soon as I posted something like this I would see people setting cookies all over the place. Cookies are very bad in some people’s eyes. You can read more about that in my original cookie reference piece. But furthermore… these things are hard!
Setting a cookie using
Why Set Cookies?
There are two main reasons that I can think of. The first is to “remember” information. Someone comes to your page and offers you his or her name. Next time, you greet them by that name. Clever, and a nice touch. But again, many people are wary of cookies and won’t feel comfortable accepting a cookie just so you can say “hi” at some later date.
The second reason, and the one I feel is most important, is moving information across pages. Someone chooses something on one page, and when they click to go to the next page, what they chose before is now posted there for them. It’s the whole basis for a shopping cart program.
My Cookie Script In Action
First off, this script is one I put together by heavily borrowing from the cookie script submitted by Giedrius. (That’s all…just “Giedrius”)
Any time you set a cookie, you need to gather some information. Usually it’s done in the format I’m showing here. Someone enters something into a text box, a button is clicked, and the cookie is written that contains the information provided by the reader.
Once the cookie is written, you can call upon it again and again. Try this:
Enter A Word:
Now… Click to go to another page.
I should tell you up front, at the moment, the script will not post multiple words in the text box. It’s easily fixed, but I’m trying to keep things pretty simple here, so just enter one word.
Setting the Cookie
Yes, it’s not that stunning as is, but it gets the point across. If I had you enter your first name, then I could have welcomed you again and again each time you arrived. If this was an order form, the next page would have the number you ordered already posted to the page. Get the picture?
Let’s start with the setting of the cookie. It’s actually a little easier than the retrieval.
cookie_name = “dataCookie”;
var YouEntered;
function putCookie() {
if(document.cookie != document.cookie)
{index = document.cookie.indexOf(cookie_name);}
else
{ index = -1;}
if (index == -1)
{
YouEntered=document.cf.cfd.value;
document.cookie=cookie_name+”=”+YouEntered+”; expires=Monday, 04-Apr-2010 05:00:00 GMT”;
}
}
I know that at this point most people quickly copy and paste the code. When you do, be careful of this line:
document.cookie=cookie_name+”=”+YouEntered+”; expires=Monday, 04-Apr-2010 05:00:00 GMT”;
The code above is on two lines. That’s bad. Make sure it all goes on one line. The width of the page made it break. Fix that when you paste it.
Start from the bottom…
When I talk about a script that deals with an HTML form tag, I like to start with them. So, here goes:
The form creates a text box and a button to fire up the function putCookie(). See that? The NAME of the form itself is “cf” and the NAME of the text box is “cfd”. Now, when we want to grab what is written in the text box, we create the hierarchy statement: document.cf.cfd.value.
With me? Good. Moving to the script, we’ll take it from top to bottom:
This starts any JavaScript.
cookie_name = “dataCookie”;
var YouEntered;
The first line names the cookie. A variable “cookie_name” is created and the name I will call this cookie, “dataCookie”, is assigned.
The second line simply sets a variable named “YouEntered”. We’ll assign a value to it later.
function putCookie() {
Here’s the function name that is called for in the form button. Remember that?
if(document.cookie != document.cookie)
{index = document.cookie.indexOf(cookie_name);}
else
{ index = -1;}
Now to the meat of the script. The first thing we do is check to see if there even is a cookie. The line if(document.cookie != document.cookie) asks if the current cookie is not equal to the data entered by the user.
Writing that question actually saves a step. By asking if something is not equal to something else, I also ask if that something even exists. You see, if it doesn’t exist, then it cannot be equal. Get it? I’m basically assuring that the cookie is rewritten each time the function is run.
This is an If/Else conditional statement, so here are the items:
- If the cookie and the data do not equal, then set the cookie with the “cookie_name” “dataCookie”.
- If they do not equal, then index is equal to negative one (-1).
Why (-1)? Because JavaScript counts everything starting at zero, so to say to JavaScript that there is actually zero, you need to go one belowzero… that’s minus one.
if (index == -1)
{
YouEntered=document.cf.cfd.value;
document.cookie=cookie_name+”=”+YouEntered+”; expires=Monday, 04-Apr-2010 05:00:00 GMT”;
}
Another If statement writes to the cookie. Now the variable name “YouEntered” is assigned the value entered into the text box using the “document.cf.cfd.value” hierarchy statement.
Finally, the document.cookie is written with the name, what the user entered, and a time for it to expire. I have the expire in this script set pretty far into the future. You can set yours to whatever you want, just follow the format shown in the script.
The final curly bracket and /SCRIPT round out the script. The cookie is set. Now we have to go get it.
What’s It Look Like?
So, you’ve set the cookie, but what does it look like? Like this:
dataCookie
Goodies
~~local~~/D:HTML GoodiesWorking
029139128323006968326349104029281635*
I have the pieces all on separate lines. In the cookie itself this was all on one line. See the parts? There’s the name of the cookie, the word I entered, where the cookie was set (from my hard drive), and then a really long number. That’s the number of milliseconds until the expire date.
Retrieve the Cookie
Okay, we’re set. A cookie has been written, but it’s not much good to us unless we can go get it.
I’ll show you this in two parts, the JavaScript code that grabs the cookie information and then the HTML/JavaScript that posts it to the page. The following is the code that appeared on the page you went to after setting the cookie.
The Retrieval Script
It looks like this:
cookie_name = “dataCookie”;
var YouWrote;
function getName() {
if(document.cookie)
{
index = document.cookie.indexOf(cookie_name);
if (index != -1)
{
namestart = (document.cookie.indexOf(“=”, index) + 1);
nameend = document.cookie.indexOf(“;”, index);
if (nameend == -1) {nameend = document.cookie.length;}
YouWrote = document.cookie.substring(namestart, nameend);
return YouWrote;
}
}
}
YouWrote=getName();
if (YouWrote == “dataCookie”)
{YouWrote = “Nothing_Entered”}
After hitting the last script, this one should fall together pretty easily. We’ll start after the
The first simply prints it to the page, the second puts it into a text box. Note the code that creates the text box requires the