Building the Registration and Configuration Settings Page

In this chapter, William needs to develop an HTML page for the Reporting Web site that collects information about visitors and their configuration preferences. To accomplish this task, William will define an HTML form and use an embedded VBScript to validate its contents. Ultimately, the page will save each visitor's name and configuration preferences in a cookie stored locally on the visitors' computers.

Cookie Basics

Using global variables, you can store and reference values during the life of a script. However, these values are lost when the script ends, and they must be recreated the next time it runs. In order to build an interactive site and to provide a mechanism that allows visitors to specify personalized configuration settings, you need a way to store data that will outlive the lifetime of your scripts or a visitor's session at your Web site. One way to provide for persistent storage (the ability to reference data provided by visitors when they return to your Web site) is to use cookies.

A cookie is a text string that your Web site can store on visitors' computers. Cookies have been around since the early days of the Internet and were designed to provide a way of storing small amounts of data on visitors' computers. Today, powerful Web servers with back-end databases are capable of storing and retrieving enormous amounts of information about visitors, their preferences, and their actions. For a Web site like the Reporting Web site, where information is available for viewing but no actual data collection or processing is performed, using a back-end database to store a few pieces of information about visitors and their preferences is overkill. A much simpler solution is to use cookies.

Cookies provide an efficient means of storing all kinds of information. For example, using cookies you can:

  • Store persistent data
  • Provide a means of differentiating between visitors
  • Provide a personalized experience
  • Track user activity
  • Store user preferences
  • Store information about a user

A cookie is a text string that you can store in the browser's memory. By default, cookies expire when the visitor closes the browser. However, by setting an expiration date when you create a cookie, you can instruct the browser to retain your cookie. Browsers accommodate this request by saving a text copy of the cookie on their computer's local hard drive.

  Note

Modern browsers provide users with the ability to block cookies. However, most users find it inconvenient or impractical to do so. It is important to understand that your scripts cannot actually store a cookie on the hard drives of the people that visit your Web site. Instead, you store the cookie in the browser's memory, and the browser decides whether or not to store the cookie on its computer's hard drive, based on browser configuration settings specified by its owner.

Cookie Storage

The way that cookies are stored on client computers depends on the type and version of the browser used to store the cookie, as well as the operating system being used to run the browser. For example, Netscape Communicator stores its cookies as text strings in one large text file located by default in C:Programs FilesNetscapeUsersUsernamecookies.txt. Internet Explorer, on the other hand, stores cookies as individual text files. On computers running Windows 95, 98, or Me, Internet Explorer stores cookie files by default in C:WindowsCookies. On computers running Windows 2000 or XP, Internet Explorer stores cookie text files by default in C:Documents and SettingsUsernameCookies.

  Note

A truly detailed discussion of cookies is beyond the scope of this book. If you are interested in learning more than the basics presented in this chapter, visit http://www.cookiecentral.com.

Internet Explorer is the browser used by employees at Intuit. This browser stores all its cookies as individual text files, as demonstrated in Figure 29.1.

click to expand
Figure 29.1: Internet Explorer stores cookies as individual text files and associates them with specific individuals

As you can see in Figure 29.1, Internet Explorer associates the visitor's username with each cookie when storing it. It does this to accommodate the possibility that multiple users may share the same computer. However, the usernames are never returned to the Web site that created the cookie; only the actual data stored in the cookie is returned (less the expiration date).

Cookies can be up to 4KB in size. All major browsers support cookies, including Netscape Communicator and Internet Explorer. Both of these browsers limit the number of cookies that can be stored on a computer to 300. The maximum number of cookies that a Web site can store on a visitor's computer is 20. In the event that either of these two thresholds is exceeded, the browser has to delete existing cookies to make room as new ones arrive. As a result of these limitations, cookies are limited to a collective maximum size of 1.2MB (per user) on any computer.

Cookies and Security

By default, cookies can only be accessed from the site that created them. This means that other Web sites will not be able to read your cookies off of a computer that has been used to visit your Web site. Likewise, you will only be able to retrieve cookies that your Web site was responsible for creating. Therefore, cookies can be seen as being somewhat secure. However, because cookies are stored as plain text files on client computers, they are freely visible to anyone with local access to them. This makes cookies inappropriate for storing sensitive pieces of information, such as credit card and social security numbers. Another limitation of cookies is that they are stored locally on the computer. If the visitor returns later to the Web site using another computer, there is no way to reassociate the data previously provided by the visitor. The data will have to be collected again if the user wants to reestablish her configuration settings.

Cookie Syntax

Your VBScripts can create and retrieve cookies using the document object's cookie property. Cookies consist of one or more parameters, each of which is separated by a semicolon (;). The syntax used to create cookies is shown below.

name=value [;expires=ExpDate] [;domain=DomName] [;path=PathName] [;secure]

Name specifies the name of the cookie. Value identifies the string of data to be stored by the cookie. ExpDate specifies a date that determines how long the cookie remains valid. DomName specifies an alternative host name from which the cookie may be accessed. Path specifies the top-level folder on the Web server from which cookies created by the Web server can be retrieved. Secure is a Boolean value that when set equal to True requires an HTTPS connection in order to create the cookie. Of all these parameters, only name and value are required when creating a cookie.

Creating and Retrieving a Simple Cookie

The following example demonstrates how to create a cookie named VisitorName and assign it a value of Jerry.

document.cookie = "VisitorName=Jerry"

Once created, the cookie can be retrieved, as shown below.

strVisitorName = document.cookie

If the visitor's computer does not have the cookie, an empty string is returned. In the previous example, the string that makes up the cookie is assigned to a variable called strVisitorName. Once the cookie is retrieved, you may use any of VBScript's string manipulation functions to parse out the data stored in the cookie.

Creating Persistent Cookies

Unless you explicitly specify an expiration date, your cookies will be deleted as soon as your visitors close their browsers. To make a cookie persistent, set its expiration date to a value that will last longer than the current browser session.

The following example demonstrates how to create a cookie that stores a visitor's name in a cookie that will persist for one year.

dtmExpDate = Weekdayname(DatePart("w",Date())) & ", "

dtmDayValue = DatePart("d",Date())

If Len(dtmDayValue) = 1 Then
 dtmDayValue = "0" & dtmDayValue
End If

dtmExpDate = dtmExpDate & dtmDayValue & "-" _
 & Monthname(DatePart("m",Date(),1) ) & "-" _
 & DatePart("yyyy",Date()) + 1 & " 00:00:00 GMT"

strCookie = "VisitorName=Jerry" & "; expires=" & dtmExpDate

The first statement creates a variable named dtmExpDate by retrieving the current date using the Date() function. It then uses the DatePart() function to extract a numeric value representing the day of the week. This value is then fed to the Weekdayname() function in order to determine the name of the current day of the week (in this example, the current day of the week is Friday). A ", " string is then appended to the name of the day of the week.

The next statement retrieves a numeric value representing the current month using the Date() and DatePart() functions. The Len() function is then used to determine whether this value is one or two digits long. If it is just one digit long (the month is between January and September), a zero is appended to the front of it to create a two-digit value.

Next the value of dtmExpDate is modified by appending the two-digit month value to it followed by the "-" string and then the name of the current month (Monthname(DatePart("m",Date(),1))). Then another "-" string and a numeric value representing the next year (by adding 1 to the current year) is appended, followed by the "00:00:00 GMT" string.

The end result is a cookie string that expires one year from the day that it is created. For example, if today is May 2, 2003, the cookie string would resolve to:

VisitorName=Jerry; expires=Friday, 02-May-2004 00:00:00 GMT
  Note

The expiration date is not returned when you later retrieve the cookie's contents.

Specifying Valid Host Names

The domain parameter provides the ability to specify what host names on your site have access to your cookie. By default, the host name of the Web server that creates the cookies is automatically assigned. Using the domain parameter, you can allow other domains that belong to you to access your cookie. For example, if you created a cookie on a server at http://www.intuitmechanical.com, it would, by default, only be accessible from that site. However, if the company had a second site, such as http://sales.intuitmechanical.com, the cookie would not be accessible from this site. Using the domain parameter, you can make the cookie available on both sites, as demonstrated below. Note that the leading dot (in.intuitmechanical.com) is required.

document.cookie = "string=" & strCookieString & ";domain=.intuitmechanical.com"
  Note

Because Intuit only has one Web server, William does not need to include this parameter when creating the Order/Inventory Reporting Web site's cookie.

Determining Which Folders Have Cookie Access

The browser's default behavior allows cookies to be accessed by pages located within the same folder as the page that created the cookie. The browser also allows the cookie to be accessed by any page that resides in subfolders of that folder. However, access from other folders on the Web server is automatically blocked.

For example, suppose the following folder structure was in place on the Intuit Web server:

  • IntuitOrderInventoryReportingHTML
  • IntuitOrderInventoryReportingRpts
  • IntuitOrderInventoryReportingRptsMay
  • IntuitOrderInventoryReportingHTMLJune

If you had an HTML page located in the IntuitOrderInventoryReportingRpts folder that created a cookie, that cookie would be accessible by other HTML pages located in that folder, as well as by HTML pages located in its two subfolders. However, the cookie would not be accessible from the IntuitOrderInventoryReportingHTML folder.

Using the path parameter, you can specify a higher-level folder from which the cookie should be accessible. For example, the following statement creates a cookie that can be accessed from any HTML page located in any folder on the Intuit Web site (or Web server).

document.cookie = "string=" & strCookieString & ";expires=" & dtmExpDate &
";path=/"

Requiring Secure Cookie Access

The final cookie parameter is the secure parameter. The secure parameter is a Boolean value that determines whether or not a cookie can be created when a secure protocol (such as HTTPS) is not being used. When set equal to True, the cookie is saved only if HTTPS is in use. When set to False, the cookie is saved regardless of whether HTTP or HTTPS is being used to connect to the Web site. For example, the following statement creates a cookie only if the visitor has established an HTTPS session to the Web site.

document.cookie = "string=" & strCookieString & ";expires=" & dtmExpDate & "; True"

Deleting Cookies

Deleting a cookie is a two-step process. First, you must create a new cookie string and set its value to null. Next, before saving the cookie, you must assign it an expiration date that is in the past. If you skip the first step and simply resave an existing cookie using an expired expiration date, your cookie will eventually be deleted (when the visitor closes the browser). However, if the visitor leaves your Web site and later returns without having closed his browser in the meantime, your cookie will still exist. By setting it equal to null and then saving it, you ensure that if the visitor returns without having first closed his browser, when you retrieve your cookie again, it will appear as if it was deleted (it will be returned a blank string).

Verifying Your Cookie s Creation

There are any number of reasons why your cookie might not get created on a visitor's computer. For example, the visitor may have configured his browser to reject cookies or to seek approval before storing one. The visitor may run software such as a personal firewall on his computer, which prohibits the collection of cookies. Regardless of the reasons, you cannot always count on your cookie being created as expected, especially when your Web site is connected to the Internet.

One way to verify that your cookie was created is to try and retrieve it immediately after creating it. If you can do this, then you'll know that you were successful in creating the cookie. If, however, you find that your cookie was not accepted, you'll need to take some type of action. For example, you might refuse to display any content except a message insisting that the visitor enable the acceptance of cookies on her browser. Alternatively, you might use default settings in place of user-specified settings in order to allow visitors to access your site without requiring them to supply you with any information. Fortunately for William, all employees' browsers at Intuit should have cookie acceptance enabled, eliminating the requirement of testing whether or not his cookies are created.


Collecting Information Using HTML Forms

The first step in creating a cookie for this project is to determine what information you wish to store in it. In the case of Intuit, William has decided to create an HTML form to collect information from visitors to the Web site. Once visitors have supplied the site's required configuration settings, a VBScript embedded within the HTML page will validate that the form has been correctly filled out and then save the visitor's personal configuration settings in a cookie. Figure 29.2 shows the HTML form that William will be creating.

click to expand
Figure 29.2: Using a form to collect each visitor's name and personal preferences

HTML for the Config html Page

The HTML required to build this form is shown below. Note that each form element is assigned an explicit Name value in order to make it easy for the VBScript to access and validate the contents of individual form elements.


 

Script 27.1 - The Order/Inventory Configuration Settings page

Order/Inventory Configuration Settings


Please tell us your name:


Default View:

Welcome Page

Report Archive Page

Daily Consolidated Summary Report

Select a color scheme: Yellow and WhiteBlue and WhiteGreen and WhiteGrey and WhitePink and White

 

The last form element on the HTML page defines a drop-down list. Figure 29.3 shows how the contents provided by this list will appear when visitors access them.

click to expand
Figure 29.3: Using a drop-down list to provide a list of choices without cluttering the display area

Using VBScript to Process Form Contents

Once the form is created, you can begin work on the VBScript that will be embedded within it. This script will perform two main tasks. The first task is to validate that the form has been correctly filled out. The second task is to store the contents of the form in a cookie.

The form contains a button at the bottom of the HTML page named SaveButton. When clicked, the button should initiate a subroutine called ProcessSettings(), as shown below.


 

The ProcessSettings() subroutine will examine each form element to ensure that the visitor has provided the required information.

Form Validation

To prepare the HTML page for its VBScript, William first embeds the opening and closing tags in the page's header section. Next he defines the following variables and constants:

Option Explicit
Dim strRadioSelected, intCounter, strConfigSettings, strRadioSelection
Const cTitleBarMsg = "Order/Inventory Configuration Settings Help Page"

Once the above steps have been completed, William creates the ProcessSettings() function, as shown below.

Function ProcessSettings()

 If Len(document.siteForm.userName.value) < 1 Then
 MsgBox "You must provide your name to continue.", , cTitleBarMsg
 Exit Function
 End If

 strRadioSelected = "False"

 For intCounter = 0 To siteForm.siteRadio.length - 1
 If siteForm.siteRadio(intCounter).Checked = "True" Then
 strRadioSelection = siteForm.siteRadio(intCounter).value
 strRadioSelected = "True"
 End If
 Next

 If strRadioSelected = "False" Then
 MsgBox "You must specify your preferred default page.", , cTitleBarMsg
 Exit Function
 End If

 strConfigSettings = document.siteForm.userName.value & "," & _
 strRadioSelection & "," & siteForm.siteList.value

 BakeTheCookie(strConfigSettings)

 top.left_frame.document.bgcolor = siteForm.siteList.value
 MsgBox " The following configuration settings have been saved:" & _
 vbCrLf & vbCrLf & _
 "Name = " & document.siteForm.userName.value & vbCrLf & _
 "Default View = " & strRadioSelection & vbCrLf & _
 "Color Scheme = " & siteForm.siteList.value, ,cTitleBarMsg

End Function

The function begins by determining whether or not the visitor entered his name in the form's text field (document.siteForm.userName.value). If a name was not supplied, the pop-up message shown in Figure 29.4 is displayed and the Exit Function statement is used to terminate the function's execution.

click to expand
Figure 29.4: Using pop-up dialog boxes to interact with visitors to ensure that they have provided required information

If the visitor did supply his name, the function next checks to see if one of the three View options was selected by examining the value of siteForm.siteRadio(intCounter).value. If one of the radio buttons was selected, its value is then assigned to a variable called strRadioSelection. Otherwise, the pop-up dialog box shown in Figure 29.5 is displayed and the function stops executing.

click to expand
Figure 29.5: If a radio button is not selected, a dialog box appears

Finally, a string is created that contains the values specified by each of the form's elements. This string is then assigned to a variable called strConfigSettings. Next the BakeTheCookie() function is called and passed the string that was just created by the ProcessSettings() function. When control is returned from the BakeTheCookie() function, the value assigned to top.left_frame.document.bgcolor is set equal to the color specified to siteForm.siteList.value. The end result is that the background color displayed in the Default.html page's left_frame frame is immediately changed to reflect the visitor's preference. Lastly, a pop-up dialog box is displayed, informing the visitor that his configuration settings have been saved. Figure 29.6 shows the pop-up dialog box that is displayed when the visitor's settings are successfully collected.

click to expand
Figure 29.6: Displaying the configuration settings specified by the visitor

Baking a Cookie

The BakeTheCookie() function formats the test string that makes the cookie and then uses the document object's cookie property to save the cookie.

Function BakeTheCookie(strCookieString)

 Dim dtmExpDate, strCookie

 dtmExpDate = Weekdayname(DatePart("w",Date())) & ", " _
 & FormatDate(DatePart("d",Date())) & "-" _
 & Monthname(DatePart("m",Date(),1) + 1) & "-" _
 & DatePart("yyyy",Date()) _
 & " 00:00:00 GMT"
 strCookie = "string=" & strCookieString & ";expires=" & dtmExpDate
 document.cookie = strCookie
End Function

Formatting a Cookie Expiration Date

One additional function is required to complete the HTML page's embedded VBScript. It is named FormatDate(). Its job is to pad the beginning of the dtmInputDate with a zero if it is only one character long.

Function FormatDate(dtmInputDate)
 If Len(dtmInputDate) = 1 Then
 dtmInputDate = "0" & dtmInputDate
 End If
 FormatDate = dtmInputDate
End Function

Canceling a Change to Configuration Settings

William anticipates that from time to time, visitors will begin making a change on the Registration and Configuration Settings page, and after thinking about it, they'll decide not to save their changes. To help make things easier for these visitors, William has added the CancelButton_onClick() subroutine to the page's embedded VBScript.

Sub CancelButton_onClick()
 history.back()
End Sub

This function's name was created by appending onClick to the name assigned to the Cancel button. By naming the subroutine this way, William automatically associates it with the CancelButton button, thus facilitating its automatic execution when the button's onClick event occurs. Once executed, the subroutine uses the history object's back() method to reload the previously displayed URL back into the right_frame frame on the Default.html page.

Displaying Help

In order to help make the Registration and Configuration Settings page easier to work with, William has chosen to provide visitors with a help option. The idea is to provide visitors with instructions on how to properly complete the form when they click on the Help button. In order to provide this feature, William plans to use the VBScript MsgBox() function. But first, he must modify the tag associated with the button, as shown below.


 

William's modification causes the tag's onClick event to trigger the execution of the DisplayHelpDialog() subroutine, which is shown below.

Sub DisplayHelpDialog()
 MsgBox "All information collected by this form is required." & vbCrLf & _
 vbCrLf & vbCrLf & vbTab & "* Please tell us your name: " & _
 "- Enter your first and last name." & vbCrLf & vbCrLf & _
 vbTab & "* Default View: - Select the page that you want loaded " & _
 "by default when you visit this web site." & vbCrLf & vbCrLf & _
 vbTab & "* Select a color scheme: - Select your background and " & _
 "foreground color preferences." & vbCrLf & vbCrLf & _
 vbTab & "* Save - Click on this button to save your configuration" & _
 "settings." & vbCrLf & vbCrLf & vbTab & _
 "* Cancel - Click on this button to return to the previous page "& _
 "without saving your configuration changes." & vbCrLf & vbCrLf & _
 vbTab & "* Help - Displays this help message.", , cTitleBarMsg

End Sub

The DisplayHelpDialog() subroutine makes use of the vbCrLf and vbTab constants to improve the presentation of its content. When executed, this subroutine displays the pop-up dialog box shown in Figure 29.7.

click to expand
Figure 29.7: Using the VBScript MsgBox() function to provide visitors with instructions on how to properly fill out the form


The Fully Assembled Welcome html Page

The fully assembled Welcome.html page is shown below. When loaded into the right_frame frame of the Default.html page, the Welcome.html page provides visitors to the Order/Inventory Reporting Web site with the ability to configure personal settings for the site. Using an embedded VBScript, the page will determine whether the form has been correctly filled out and, if appropriate, will store the visitor's configuration settings in a cookie.


 

Script 27.1 - The Order/Inventory Configuration Settings page

Configuration Settings

 

Please tell us your name:


Default View:

Welcome Page

Report Archive Page

Daily Consolidated Summary Report

Select a color scheme: Yellow and WhiteBlue and WhiteGreen and WhiteGrey and WhitePink and White


 


Summary

In this chapter, you learned how to collect data from visitors to your Web site using an HTML form. You also learned how to work with various form elements, as well as how to use VBScript to validate form contents and ensure that visitors supply all required data. Once valid data is collected, you can save it for future reference using cookies. You do so by building a data string that includes an expiration date and then storing that string on the visitor's computer.


Part I - Introducing Microsoft VBScriptBasics

Part II - Professional Project 1 Desktop Administration Using VBScript and the WSH

Part III - Professional Project 2 Analyzing Application Logs

Part IV - Professional Project 3 Creating a Centralized Report Management Station

Part V - Professional Project 4 Reporting Application Summary Data via the Web

Part VI - Introducing Microsoft VBScriptBasics



Microsoft VBScript Professional Projects
Microsoft VBScript Professional Projects
ISBN: 1592000568
EAN: 2147483647
Year: 2005
Pages: 366

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net