Tuesday, December 3, 2024

So, You Want To Set A Cookie, Huh?

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.


<SCRIPT LANGUAGE=”JavaScript”>

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”;
}

}
</SCRIPT>

<FORM NAME=”cf”>

Enter A Word: <INPUT TYPE=”text” NAME=”cfd” size=”20″>
<INPUT TYPE=”button” Value=”Set to Cookie”
onClick=”putCookie()”>

</FORM>


     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:

<FORM NAME=”cf”>

Enter A Word: <INPUT TYPE=”text” NAME=”cfd” size=”20″>
<INPUT TYPE=”button” Value=”Set to Cookie”
onClick=”putCookie()”>

</FORM>

     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:

<SCRIPT LANGUAGE=”JavaScript”>

     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:

<SCRIPT LANGUAGE=”JavaScript”>

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”}

</SCRIPT>

     After hitting the last script, this one should fall together pretty easily. We’ll start after the <SCRIPT LANGUAGE=”javascript”> tag.

cookie_name = “dataCookie”;
var YouWrote;

     This script assumes a cookie has been set. In fact, it assumes many cookies have been set so the name of the cookie is immediately noted. We are looking for the data found in a cookie named “dataCookie”. A variable “YouWrote” is also created. Later it will be assigned the value from the cookie. You’ll then use “YouWrote” to represent the cookie’s data.

function getName() {

     The function is called getName().

if(document.cookie)
{
index = document.cookie.indexOf(cookie_name);

     If a no cookie exists, then the index should be the one in dataCookie. But we know one exists.

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;
}
}
}

     As you saw above, it is the second piece of information in the cookie we’re interested in. This code grabs a substring of the cookie represented by the second item. It then assigns that value to YouWrote and returns it to the script.

YouWrote=getName();

     Every function must have a trigger to make it work. Here’s the one that fires up “getName()” assigning its output to “YouWrote”.

if (YouWrote == “dataCookie”)
{YouWrote = “Nothing_Entered”}

     This little blip of code is used if nothing is entered. When you submit nothing (no data) to the cookie, the name of the cookie is returned by the function. This says that if the “YouWrote” equals dataCookie, the name of the cookie, then the value assigned should be “Nothing_Entered”. It just looks a little cleaner.

Putting the Cookie on the Page

     It’s a fairly simply process from this point on. You have a variable, YouWrote, that represents the value of the cookie. Just use that variable name to post the data to the page through document.write commands. This is how I did it on the secondary page in this tutorial:

<SCRIPT LANGUAGE=”javascript”>
document.write(“You Entered ” +YouWrote+ “.”);
</SCRIPT>

<SCRIPT LANGUAGE=”javascript”>
document.write(“<FORM>”)
document.write(“You Entered:”)
document.write(“<INPUT TYPE=text SIZE=30 VALUE=” +YouWrote+ “>”);
document.write(“</FORM>”)
</SCRIPT>

     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 <FORM> tags, too.


More Than One Cookie

     The code you got here is pretty much copy-and-paste easy to install. But let’s say you want to set multiple cookies. You’ll need to remember that the two scripts you got here are links. The first sets the cookie, the second retrieves it. So any changes you make to one script, you’ll need to make to the other.

     First and foremost, you’ll need to set a new cookie name, then new variable names to represent the data. Please note that those variable names appear throughout the script, so make sure you get them all. I do it with my text editor’s “Replace All” function.

     If you grab the cookie the way I did, using a form, then you’ll need to make sure the form element’s NAMEs are correctly represented in the script’s hierarchy statements.

     Don’t sweat it. It’s a little work, but you’ll get it down soon enough. Just remember to keep a backup of the original working scripts. I wasted over an hour this time around by editing the original. That’s what I get for writing a JavaScript book….

Enjoy!

[Why Set Cookies?] [My Cookie Script In Action]
[Setting the Cookie] [What’s It Look Like?]
[Retrieve the Cookie] [More Than One Cookie]

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured