JavaScript Editor JavaScript Validator     JavaScript Editor 



Team LiB
Previous Section Next Section

Creating a Cookie

To make life easier for ourselves, we'll write a function that allows us to create a new cookie and set certain of its attributes with more ease. We'll look at the code first and create an example using it shortly.

function setCookie(cookieName, cookieValue, cookiePath, cookieExpires)
{
   cookieValue = escape(cookieValue);
   if (cookieExpires == "")
   {
      var nowDate = new Date();
      nowDate.setMonth(nowDate.getMonth() + 6);
      cookieExpires = nowDate.toGMTString();
   }
   if (cookiePath != "")
   {
      cookiePath = ";Path=" + cookiePath;
   }
   document.cookie = cookieName + "=" + cookieValue +
      ";expires=" + cookieExpires + cookiePath;
}

The secure and domain parts of the cookie string are unlikely to be needed, so we just allow the name, value, expires, and path parts of a cookie to be set by the function. If we don't want to set a path or expiration date, we just pass empty strings for those parameters. If no path is specified, the current directory and its subdirectories will be the path. If no expiration date is set, we just assume a date six months from now.

The first line of the function introduces the escape() function, which we've not seen before.

cookieValue = escape(cookieValue);

When we talked about setting the value of a cookie, we mentioned that certain characters cannot be used directly, such as a semicolon. (This also applies to the name of the cookie.) To get around this problem, we can use the built-in escape() and unescape() functions. The escape() function converts characters that are not text or numbers into the hexadecimal equivalent of their character in the Latin-1 character set, preceded by a % character. This character set can be found in Appendix D.

For example, a space has the hexadecimal value of 20, and the semicolon has the value of 3B. So, the following code produces the output shown in Figure 11-13.


Figure 11-13
alert(escape("2001 a space odyssey;"));

We can see that the spaces have been converted to %20, % indicating that they represent an escape or special character rather than an actual character, and that 20 is the ASCII value of the actual character. The semicolon has been converted to %3B, as we'd expect.

As we'll see later, when retrieving cookie values we can use the unescape() function to convert from the encoded version to plain text.

Back to our function; we next have an if statement.

   if (cookieExpires == "")
   {
      var nowDate = new Date();
      nowDate.setMonth(nowDate.getMonth() + 6);
      cookieExpires = nowDate.toGMTString();
   }

This deals with the situation where an empty string, "", has been passed for the cookieExpires parameter of the function. Because most of the time we want a cookie to last longer than the session it's created in, we set a default value for expires that is six months after the current date.

Next, if a value other than an empty string ("") has been passed to the function for the cookiePath parameter, we need to add that value when we create the cookie. We simply put "path=" in front of any value that has been passed in the cookiePath parameter.

   if (cookiePath != "")
   {
      cookiePath = ";Path=" + cookiePath;
   }

Finally on the last line we actually create the cookie, putting together the cookieName, cookieValue, cookieExpires, and cookiePath parts of the string.

   document.cookie = cookieName + "=" + cookieValue +
      ";expires=" + cookieExpires + cookiePath;

We'll be using the setCookie() function whenever we want to create a new cookie because it makes setting a cookie slightly easier than having to remember all the parts we want to set. More importantly, it can be used to set the expiration date to a date six months ahead of the current date.

For example, to use the function and set a cookie with default values for expires and path we just type the following:

setCookie("cookieName","cookieValue","","")

Try It Out – Using setCookie()

We'll now put this together in a simple example in which we use our setCookie() function to set three cookies named Name, Age, and FirstVisit. We then display what is in the document.cookie property to see how this has been affected.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script language="JavaScript" type="text/JavaScript">
function setCookie (cookieName, cookieValue, cookiePath, cookieExpires)
{
   cookieValue = escape(cookieValue);
   if (cookieExpires == "")
   {
      var nowDate = new Date();
      nowDate.setMonth(nowDate.getMonth() + 6);
      cookieExpires = nowDate.toGMTString();
   }
   if (cookiePath != "")
   {
      cookiePath = ";Path=" + cookiePath;
   }
   document.cookie = cookieName + "=" + cookieValue +
      ";expires=" + cookieExpires + cookiePath;
}
setCookie("Name","Bob","","");
setCookie("Age","101","","");
setCookie("FirstVisit","10 May 2000","","");
alert(document.cookie);
</script>
</head>
<body>
</body>
</html>

Save the example as CreateCookie.htm, and then load it into a web browser.

We'll see the alert box shown in Figure 11-14. Note that all three cookies are displayed as name/value pairs separated by semicolons, and also that the expiration date is not displayed. If we had set the path parameter, this also would not have been displayed. The UserName cookie from a previous example is also displayed.

Click To expand
Figure 11-14

How It Works

We've already seen how the setCookie() function works, so let's look at the three lines that use the function to create three new cookies.

setCookie("Name","Bob","","");
setCookie("Age","101","","");
setCookie("FirstVisit","10 May 2000","","");

It is all fairly simple. The first parameter is the name that we'll give the cookie. We see shortly how we can retrieve a value of a cookie based on the name we gave it. It's important that the names we use are only alphanumeric characters, with no spaces, punctuation, or special characters. Although we can use cookie names with these characters, it's more complex to do so and is best avoided. Next we have the value we want to give the cookie. The third parameter is the path, and the fourth parameter is the date we want the cookie to expire on.

For example, take the first line where we use the setCookie() function. Here we are setting a cookie that will be named Name and have the value Bob. We don't want to set the path or expires parts, so we just pass an empty string, that is, "". Note that we must pass "" –. We can't pass nothing at all.

The remaining two lines in the previous code snippet set the cookies named Age and FirstVisit and set their values to 101 and 10 May 2000.

If we did want to set the path and the expiration date, how might we change our code?

Well, imagine that we want the path to be /MyStore and the expiration date to be 1 year in the future. Then we can use the setCookie() function in the following way:

var expireDate = new Date();
expireDate.setMonth(expireDate.getMonth() + 12);
setCookie("Name","Bob","/MyStore",expireDate.toGMTString());

First we create a new Date object, and by passing no parameter to its constructor, we let it initialize itself to the current date. In the next line, we add 12 months to that date. When setting the cookie using setCookie() we pass "/MyStore" as the path and expireDate.toGMTString() as the expires parameter.

What about the situation where we've created our cookie, say, named Name with value of Bob, and we want to change its value? To do this we can simply set the same cookie again, but with the new value. To change the cookie named Name from a value of Bob to Bobby we'd need the following code:

setCookie("Name","Bobby","","");

What if we want to delete an existing cookie? Well that's easy. Just make it expire by changing its value and setting its expiration date to a date in the past, as in the following example:

setCookie("Name","","","Mon, 1 Jan 1990 00:00:00");

Team LiB
Previous Section Next Section


JavaScript Editor JavaScript Validator     JavaScript Editor


©

R7