Vol. 1, No. 17
Intro to Cookies
In recent installments of Handcrafted, we've gone over the essentials of JavaScript and how to call up a function. Hopefully, you've been able to create some gorgeous (and cross-platform compliant) mouseover events. (New subscribers or those wishing for a refresher course may want to check out our recent JavaScript tutorial.)
Now that we're all up to speed, let's get going! Today we're going to make cookies fat-free, delicious JavaScript cookies. They're the kind you feed to all of your visitors, so that when they come back to your site, you know who they are and what they did last time they visited.
Here's how it works: You acquire data from your visitor. (For our purposes, we'll have them type it in, but feel free to experiment with data acquired in other ways usage patterns and so forth.) Save it in the form of a cookie to their hard drive. When they return to your site using the same computer and browser, your site will then read the cookie from their hard drive and "remember" who they are.
A note of acknowledgement: This cookie lesson is taken substantially from Thau's invaluable Advanced JavaScript Tutorial on Webmonkey. All of the code we'll be learning is his. If you want to fully understand how his cookie code works, or if you want to be able to adapt it for your own purposes, don't miss his outstanding tutorial! The omniscient Thau taught everyone who's anyone in the world of JavaScript.
Let's first take a look at the code used to create a cookie; then we'll examine what it does, line by line. Here's a sample page that asks for the user's name and saves the information as a cookie:
<HTML>
<HEAD>
<TITLE>Cookie time!</TITLE>
</HEAD>
<BODY>
<SCRIPT language="JavaScript">
<!--
function setCookie()
{
var the_name = prompt("What's your name?","");
var the_cookie = "testcookie=username:" + escape(the_name);
document.cookie = the_cookie;
alert("Thanks.");
}
// -->
</SCRIPT>
<A HREF="#" onClick="setCookie(); return false;">Try me.</A>
<A HREF="nextpage.html">Read me my cookie.</A>
</BODY>
</HTML>
Within this function, the first line brings up a name prompt and saves the result in the variable "the_name." The next line puts the name information in cookie format. First it runs "escape()" on the input, to encode it as a nice, clean string. (Take note: Cookies cannot have spaces, commas, or semicolons. Spaces will be automatically replaced by "%20.") The script then creates the actual text of the cookie that will be saved. Assuming your name is Billy, the text will read: "testcookie=username:Billy" ("testcookie" being the name of the cookie). The cookie's text is stored in the variable "the_cookie." The next line of code saves the cookie on the remote computer. Finally, the "alert" line calls for a popup message that you can set. That's it; this cookie is ready for munching! See the code in action.
Now that you've saved your visitor's data on their computer, you need to be able to detect and read it upon their return visit. (Getting them to come back to your site is a whole other ball game.) You'll notice that the last line of code in the page we just made is a link to a new page. Here's what should happen on that page:
<HTML>
<HEAD>
<TITLE>What's my name?</TITLE>
</HEAD>
<BODY>
<SCRIPT language="JavaScript">
<!--
function readCookie()
{
var the_cookie = document.cookie;
var broken_cookie = the_cookie.split(":");
var the_name = broken_cookie[1];
var the_name = unescape(the_name);
alert("Your name is: " + the_name);
}
// -->
</SCRIPT>
<A HREF="#" onClick="readCookie(); return false;">What's my name?</A>
</BODY>
</HTML>
This is a simple way to read a cookie. The first line of code finds the text of any cookie for the site with the "document.cookie" property, and stores that string in the "the_cookie" variable. The string, as you recall, is "testcookie=username:Billy." The challenge is to single out the actual name from within the cookie. The second line of the script divides the cookie into two pieces, using a wonderful split method one before the colon, one after and saves them as two elements in an array variable. We don't care too much about the first part "broken_cookie[0]"; for this purpose, we want the part after the colon, which happens to be stored as "broken_cookie[1]." We'll save that value in the variable "the_name." Now all we have to do is decode it back into plain text with "unescape()" and display the results, summarily impressing everyone! See this code in action.
That's all there is to it! You may want to get the user's data from an HTML form instead of a popup box, which is easily done once you know the basics. There are two ways to save multiple bits of data in cookie format. You can put them all in one cookie (up to 4 KB), which is divided by any character (I like semicolons) using the split method. Or you can save your data in multiple cookies (each Tripod member can set up to 20 cookies). Multiple cookies are set and retrieved simply by giving the cookies different names. When you set "document.cookie," it adds rather than replaces the new data to the end of the existing data. That way, you can add cookies to cookies. When you encode multiple bits of data in a single cookie, it will look something like this:
var big_cookie = "name:Polly;species:cat;easilybored:yes";
You'll need to "big_cookie.split" it first into its three "field:value" pairs. Then split those pairs to extract the relevant data the data found after the colon. This method will automatically save the split pieces into nice related arrays. While this may seem tedious, it's actually quite easy.
HINTS, POINTERS, and TIPS o' the TRADE
For many applications, it will be best if the cookie you set doesn't survive the closing of the user's browser. That's the case with the cookie shown above. Sometimes, though, you'll want the cookie to stick around until the user comes back to your site. In order to do that, you'll have to give it an expiration date. This is explained in Thau's estimable tutorial.
Speaking of Thau's tutorial, have you read about setting cookie paths?
For relief from localized sunburns, try applying moist, used teabags.
RESOURCES:
Thau's Basic JavaScript Tutorial
Thau's Advanced JavaScript Tutorial
Thau on Cookies
Webmonkey's Introduction to Cookies
The Webmonkey Cookie Library