Chapter 24
Script Example 7: Welcome Back

In This Chapter

A Warm Welcome

Everyone enjoys a warm welcome, even from a Web site. Back in Chapter 17, “Care for a Cookie?,” you learned how a Web page can “remember” information about a visitor. Cookies make it possible to store information on a user’s hard drive (or in his RAM), which can be retrieved when and if that person—or someone else using his computer—revisits the page.

In Chapter 17, you used a basic example of a cookie that “remembered” the time and date of a user’s last visit to the page. Let’s elaborate on that example in this chapter, and create a Welcome Back page, that meets the following criteria:

The major functions of this program are quite similar to those from Chapter 17; but they do boast a few additional enhancements. As usual, you’ll begin by looking at each function of the Welcome Back program.

Constructing the Cookie

The cookie will be saved on two occasions: after the user enters his name (if this is his first visit to the page) and upon visiting the page (if this is not the user’s first visit).

Remember that for a single cookie, you can store one string of information. However, you can cleverly pack as much useful data into this string as possible. When you code your GetCookie() function, you’ll untangle the data to pull out the information you stored.

In this example, the cookie value actually contains three pieces of data: the date/time, the user’s name, and the total number of visits so far. You’ll pack this data into the single cookie named lastvisit, as follows:

By doing this, you can use the GetCookie() function to pull the date (the characters prior to the underscore), the user’s name (the characters between the underscore and the pound sign), and the total number of visits (the characters to the right of the pound sign).

Setting Cookie

With that preamble, here is the code for SetCookie():

function SetCookie(name)
{
cookidx++
today = new Date ()
expdate = new Date ()
expdate.setTime(expdate.getTime() + (24 * 60 * 60 * 1000 * 365))
expdate=expdate.toGMTString()
document.cookie="lastvisit="+escape(today)+"_"+name+"#"+cookidx+"; expires="+expdate+";"
}

Notice that SetCookie() takes one parameter, name, which is the name of the cookie. In this example, calls to SetCookie will pass it the name lastvisit because that’s the only cookie this page uses.

Aside from that, this function is not unlike that in Chapter 17. The current date and time is calculated, and then a concatenated string containing the date, the user’s name, the visit total (cookidx), and the expiration date is assigned to the cookie. Note also, though, cookidx, which is the counter to keep track of the user’s visit total. At the top of this function, cookidx is incremented by one to add the current visit to the total.

Getting Cookie

Moving along, the “opposite” of SetCookie() will be GetCookie(). The object of GetCookie() is clear enough: to retrieve the cookie information and decode it into useful data. Although the following function may look complicated, it’s not quite so bad. First it uses a while loop to locate and extract the cookie value from the entire cookie, and then it parses that value for the date, user name, and visit total.

function GetCookie (name)
{
var namestr = name + "="
var namelen = namestr.length
var cooklen = document.cookie.length
var i = 0
while (i < cooklen)
{ var j = i + namelen
if (document.cookie.substring(i, j) == namestr)
{ endstr = document.cookie.indexOf (";", j)
if (endstr == -1) {endstr = document.cookie.length}
tempstr = unescape(document.cookie.substring(j,endstr))
//entire cookie value extracted into tempstr, now we can parse for details 
cookdate = tempstr.substring(0,tempstr.indexOf("_"))
cookname = tempstr.substring(tempstr.indexOf("_")+1,tempstr.indexOf("#"))
cookidx = tempstr.substring(tempstr.indexOf("#")+1,tempstr.length)
return tempstr 
}
i = document.cookie.indexOf(" ", i) + 1
if (i == 0) break
}
return null
}

If GetCookie() fails to find a cookie with the specified name (e.g. lastvisit), it returns a null value. Otherwise, cookdate contains the date and time, cookname contains the user’s name, and cookidx contains the visit total.

Canceling Cookie 

Lastly, you need a function to delete the cookie, in case the user wants to eliminate the record of his visit. Though not vital, this is a courtesy function: Many Web surfers don’t appreciate someone keeping track of them without their consent. If you provide a delete cookie function, the user at least has the opportunity to “cover his tracks.”

function DeleteCookie (name)
{
var expdate = new Date()
expdate.setTime (expdate.getTime() - 1000000000)
document.cookie= name + "=" + GetCookie(name) + "; expires=" + expdate.toGMTString()
location=thispage
}

Deleting the cookie isn’t terribly difficult. Above, the current date is determined, and then a value representing a date in the past is assigned to expdate. The cookie is then re-saved with the new expiration date. Because this expiration date is before the current date, the cookie is now expired and, therefore, cannot be retrieved by the Web browser.

Finishing Touches

Having written the heart of the Welcome Back program, you only need to add some Web page content to make use of those functions.

In this case, you don’t know for certain which Web page content to display. After all, if this is the user’s first visit to the page (in which case, GetCookie() returns null because the cookie is non-existent or expired), you want to display a formal greeting and a request that the user enter his name to create the cookie. On the other hand, if this is a repeat visit, you want to display some customized content such as “Welcome back, Bill! This is visit #3, your last being on September 9, 1996.” It’s not unlike the well-known letter from Publisher’s ClearingHouse, but the key is not to overdo the custom content (as in “Welcome to my page, BILL. Here, BILL, you will find information of interest to BILL.”) You know what I mean.

To achieve that goal, you write some JavaScript code outside of a function. Instead, it simply resides between the <BODY> tags, where normal HTML code usually goes. As a result, this JavaScript code will automatically execute whenever the page is loaded.

The above code revolves around a basic if statement: if GetCookie() does not return null (therefore the cookie exists, and this is not a first visit), a series of document.writeln statements constructs the “Welcome Back, so-and-so” greeting. Also note that a button is created with an onClick event handler to call the DeleteCookie() function, as a courtesy to the user. Alternatively, if GetCookie() does return null, a different series of document.writeln statements constructs another greeting page, which contains a text field for the user to submit his name.

In cases where the user either hits the Delete Cookie button or Submits his name to create the first-time cookie, the page is automatically reloaded with the “location=thispage” statement to reflect the change (thispage having been earlier assigned the true URL of this page).

Cookies Are Served!

Here it is: The entire Welcome Back page.

When loaded into your Web browser for the first time, the Welcome Back page appears as pictured here.

The Welcome Back page upon first visitation.

Future visits to the page recall the saved cookie and generate the friendlier greeting shown in the next figure.

When you return to the Welcome Back page, you see that you haven’t been forgotten!

The Least You Need to Know

In this chapter, we returned to the theme from Chapter 17, “Care for a Cookie?,” and took it to the “next level” (as they say in sports clichés). You learned how to pack several pieces of information into a single cookie and how to extract them later. You also saw how to use JavaScript to create custom content by writing HTML code directly to the page, using the data retrieved from the cookie. Publisher’s ClearingHouse, look out!

Previous Chapter Next Chapter


Beginning of ChapterTable of ContentsBook Home PageQue Home Page


For comments or technical support for our books and software, select Talk to Us.
To order books, call us at 800-716-0044 or 317-228-4366.

© 1997, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon & Schuster Company.