Chapter 5

VBScript in Web Pages

by Craig Eddy


CONTENTS

As you'll see throughout this book, using VBScript within your Web pages enables you to create a very dynamic and interactive experience for the Web surfers who visit your site. This is true whether you have a site that is visible to the entire Internet or an intranet site visible only to users of your company's LAN or WAN.

In the early days of the Web, all that was possible was a page containing text and some links to other documents. From there, the Web evolved to use a graphical interface, enabling Web page designers to embed pictures and graphics in their pages. Along came Netscape and Java, and the Web now has the capability to use various plug-ins and client-side applications. Finally, Microsoft introduced the concept of active content, which enables the user, browser software, and Web server to communicate and interact in harmony with one another. Although this chapter doesn't go into the depth necessary to create such a harmonious Web page completely, you will learn how you can combine the capabilities of your Web server with the capabilities of VBScript to create a more dynamic site.

This chapter starts by discussing the use of VBScript to generate HTML content. You will see an example that enables users to build Web pages and display them within Internet Explorer. Next comes a discussion about combining VBScript with CGI and ISAPI applications, which are types of server-side applications. You'll see how you can use these applications to generate HTML with embedded VBScript. Not only are the Web pages generated by such applications dynamic, but the VBScript code embedded in the pages can be different with each invocation of the server-side application as well. Finally, the chapter winds up with a discussion about combining VBScript with database access. This is done using the Microsoft Internet Database Connector to generate pages based on a database query.

Using VBScript and HTML

One of the coolest features of VBScript is its capability to generate HTML on-the-fly. You can use the programming capabilities of VBScript to decide what should appear on the page and how it should appear. Then the script code can output the HTML for display within the browser window.

You can use three methods to generate HTML using VBScript: within the window_onLoad event (which fires when the page loads), embedded anywhere within the HTML file, and as a new page created on demand within the browser window. This section explores all three methods. An example is provided for the third method. More examples of this technique are presented in Chapter 13, "Dynamic Web Page Building."

Using the onLoad Event

When a page is loaded into the Internet Explorer, an event named window_onLoad fires. You can write code in your script to handle this event by adding a code section such as the one shown in Listing 5.1.


Listing 5.1. Code for the window_onLoad event.

<SCRIPT LANGUAGE="VBScript">

<!--

sub window_onLoad()

...

end sub

-->

</SCRIPT>


Any code you place within this procedure is executed when the page is loaded. You also can use the document.writeln method to output any HTML text to the page. After you finish writing the HTML, use the document.close method to close the document's output stream and actually display the HTML generated by the script.

Embedding VBScript in the HTML

In addition to using the onLoad event, you can embed VBScript code anywhere within your page's HTML. This is useful when most of your page is based on static HTML but you want to use VBScript code to display some HTML that changes with varying conditions. A good example of this is displaying the current date on the page. You also can use this technique to embed different graphics and messages, depending on any variable information to which VBScript has access: time of day, type of Web browser the user is running, and even the history list that contains the last few pages the user visited. An example of embedding the current date and time within the page is presented in Chapter 13.

Creating a New Page with VBScript

The final method discussed here involves actually creating a new Web page on-the-fly. When this method is used, the current page is cleared and the new page is displayed in its place. This technique can be used to create slide shows, for example, by embedding VBScript code within HTML generated by VBScript code. Doing so, however, eventually makes you feel like you're aiming a video camera at a monitor that's displaying the camera's output; it creates a neat effect, but you'll get dizzy if you try it for too long!

Instead, in this section you'll create a Web page that enables viewers to create their own customized pages. The example has input controls that users can interact with to decide how their pages should look. When they're ready, they click the Display Page button and the page they specified is generated and displayed. The original page is shown in Figure 5.1. The HTML for the page is given in Listing 5.2. This file also is included on the accompanying CD-ROM as 5-1.htm.

Figure 5.1 : The Create Your Own Web Page entry form.


Listing 5.2. The HTML and VBScript for the Create Your Own Web Page page.

<HTML><HEAD><TITLE>Create Your Own Web Page</TITLE></HEAD>

<BODY>

<CENTER><H2>Create Your Own Web Page</H2></CENTER>

<p>

<H3>This page contains a VBScript application and embedded ActiveX controls

that enable you to design your own basic Web page.<H3>

<p>

<table><tr><td align=RIGHT><H3>Enter the title for your page: </H3></TD><TD>

<OBJECT ID="txtTitle" WIDTH=225 HEIGHT=23

     CLASSID="CLSID:8BD21D10-EC42-11CE-9E0D-00AA006002f3">

        <PARAM NAME="VariousPropertyBits" VALUE="1749567515">

        <PARAM NAME="Size" VALUE="5962;600">

        <PARAM NAME="FontCharSet" VALUE="0">

        <PARAM NAME="FontPitchAndFamily" VALUE="2">

        <PARAM NAME="FontWeight" VALUE="0">

    </OBJECT>

</TD></TR>

<TR><TD ALIGN=RIGHT><H3>Enter a heading line for your page: </H3></TD>

<TD>

    <OBJECT ID="txtHeader" WIDTH=225 HEIGHT=23

     CLASSID="CLSID:8BD21D10-EC42-11CE-9E0D-00AA006002f3">

        <PARAM NAME="VariousPropertyBits" VALUE="675825691">

        <PARAM NAME="Size" VALUE="5962;600">

        <PARAM NAME="FontCharSet" VALUE="0">

        <PARAM NAME="FontPitchAndFamily" VALUE="2">

        <PARAM NAME="FontWeight" VALUE="0">

    </OBJECT>

</TD></TR>

<TR><TD ALIGN=RIGHT VALIGN=TOP><H3>Enter some text for your page: </H3></TD>

<TD>

    <OBJECT ID="txtMiscText" WIDTH=225 HEIGHT=125

     CLASSID="CLSID:8BD21D10-EC42-11CE-9E0D-00AA006002f3">

        <PARAM NAME="VariousPropertyBits" VALUE="2831697947">

        <PARAM NAME="ScrollBars" VALUE="2">

        <PARAM NAME="Size" VALUE="5962;3307">

        <PARAM NAME="FontCharSet" VALUE="0">

        <PARAM NAME="FontPitchAndFamily" VALUE="2">

        <PARAM NAME="FontWeight" VALUE="0">

    </OBJECT>

</TD></TR>

<TR><TD ALIGN=RIGHT VALIGN=TOP><H3>Enter any additional HTML for your page: </H3></TD>

<TD>

    <OBJECT ID="txtHTML" WIDTH=225 HEIGHT=112

     CLASSID="CLSID:8BD21D10-EC42-11CE-9E0D-00AA006002f3">

        <PARAM NAME="VariousPropertyBits" VALUE="2831697947">

        <PARAM NAME="ScrollBars" VALUE="2">

        <PARAM NAME="Size" VALUE="5962;2963">

        <PARAM NAME="FontCharSet" VALUE="0">

        <PARAM NAME="FontPitchAndFamily" VALUE="2">

        <PARAM NAME="FontWeight" VALUE="0">

    </OBJECT>

</TD></TR>

<TR><TD ALIGN=RIGHT><H3>Enter the URL for a picture to display: </H3></TD>

<TD>

    <OBJECT ID="txtPicture" WIDTH=225 HEIGHT=23

     CLASSID="CLSID:8BD21D10-EC42-11CE-9E0D-00AA006002f3">

        <PARAM NAME="VariousPropertyBits" VALUE="675825691">

        <PARAM NAME="Size" VALUE="5962;600">

        <PARAM NAME="FontCharSet" VALUE="0">

        <PARAM NAME="FontPitchAndFamily" VALUE="2">

        <PARAM NAME="FontWeight" VALUE="0">

    </OBJECT>

</TD></TR>

</TABLE>



<SCRIPT LANGUAGE="VBScript"> <!--

Sub cmdSubmit_Click()

Document.Open

document.writeln "<HTML><TITLE>" & txtTitle.Text & "</TITLE>"

document.writeln "<BODY><H1>" & txtHeader.Text & "</H1>"

document.writeln "<P>" & txtMiscText.Text & "<P>"

document.writeln txtHTML.Text

if Len(txtPicture.Text) then

    document.writeln "<P><CENTER><IMG SRC=" & txtPicture.Text

    document.writeln "></CENTER>"

end if

document.writeln "</BODY></HTML>"

document.close

document.close

end sub

--> </SCRIPT>

<CENTER>

    <OBJECT ID="cmdSubmit" WIDTH=96 HEIGHT=32

     CLASSID="CLSID:D7053240-CE69-11CD-A777-00DD01143C57">

        <PARAM NAME="BackColor" VALUE="12615935">

        <PARAM NAME="Caption" VALUE="Display Page">

        <PARAM NAME="Size" VALUE="2540;846">

        <PARAM NAME="FontCharSet" VALUE="0">

        <PARAM NAME="FontPitchAndFamily" VALUE="2">

        <PARAM NAME="ParagraphAlign" VALUE="3">

        <PARAM NAME="FontWeight" VALUE="0">

    </OBJECT>

</CENTER></BODY></HTML>


Most of Listing 5.2 is straightforward HTML with some ActiveX text boxes embedded in it. The interesting part as far as this chapter is concerned is in the script code that appears near the bottom of the listing. This code is for the Display Page button's Click event, as can be seen from the procedure's definition: Sub cmdSubmit_Click(). The code in this procedure takes the data entered in the text boxes and outputs it to a new document.

The new document is started using the document.open method. This opens a new output stream into which you can write HTML text. It also clears the document currently displayed in the browser. After this comes various document.writeln method invocations. Notice that the code is inserting HTML directly into the output stream. This capability enables you to create any type of Web page you want; you can embed video, pictures, and even ActiveX controls into the new document. Finally, the document.close method is invoked to close the output stream and display the new document.

Figure 5.2 shows the data entry page after the text boxes are populated with some sample information. Figure 5.3 shows the page created using the entries shown in Figure 5.2.

Figure 5.2 : Sample data entered into the page.

Figure 5.3 : The page resulting from the sample data.

Using VBScript and CGI/ISAPI

Most Web servers provide the capability to launch applications from a Web page and pass the application information that was entered onto the Web page. The application then produces some sort of output page based on the data it received. These applications usually are common gateway interface (CGI) or Internet server API (ISAPI) applications. They must be written to accept input from the Web server and to return data to the server in the proper format.

VBScript can be tied to CGI/ISAPI applications in both directions. First, the CGI/ISAPI application can generate an HTML document containing VBScript code. This code may depend on the data that was input into the CGI application. A user logon screen for an order entry Web site might request the country in which the user resides, for example. Then, depending on the country's standard address format, both the HTML required to create an address entry form and the VBScript code that will validate the entered address information changes. This data is output by the CGI/ISAPI application differently, depending on the country entered. A user from the United States receives a different order entry page than a user from the United Kingdom, for example, complete with the address validation code appropriate for the country.

In the other direction, it is possible to use VBScript to alter the way the Web page interacts with the CGI/ISAPI application. The script code could change the data before it is submitted to the application, for example. This is useful when the server-side application is expecting a field to be in a specific format but the Web page gives the user more flexibility in entry. The script code then can interpret the entered data and format it properly for submission.

Another use along these lines would be to expand the types of input controls that can be used to enter data. On your HTML form, for example, you might have a drop-down listbox that displays text in a verbose format, but your server-side application is expecting the data in a code format. This is almost always the case for database lookup tables such as titles or ratings. Your listbox might contain the values Chief Executive Officer, Manager, and so on, which has corresponding code values of CEO, MGR, and so on. When the HTML form is submitted, VBScript code can be used to determine which entry is selected in the listbox (using the listbox's ListIndex property) and then to submit the proper code value to the server application (probably using an array that's indexed with the ListIndexes of the corresponding listbox item). This type of page probably is generated originally by another back-end process that has access to the database where the lookup table resides.

Providing Database Access

In addition to interacting with server-side applications using VBScript, you can interact with databases located on the Web server. By using the Microsoft Internet Information Server (IIS) with the Internet Database Connector (IDC) provided with the server software, you can create a very dynamic database query and reporting tool.

This section doesn't discuss all the details of using the IDC, but you will learn how to set up an IDC script file and an output template file. This output template file embeds some pretty useful VBScript code into the page displayed in response to the IDC script. An IDC script is a file used by the IDC to generate a database query. This query can be based on HTML form input variables, or it always can execute the same SQL statement. The example presented here uses the latter method to retrieve a list of all people who have registered in a demo request database.

Defining an ODBC Datasource

Let's start by setting up an IDC connection on your IIS machine. You should have 32-bit ODBC installed on the machine. If not, you need to install it in order to use the IDC features. Run the ODBC administrator and create a system datasource by clicking the System DSN button. The IDC will work only with system datasources. In the dialog that appears, click the Add button, select the driver appropriate for the database you'll be accessing, and click OK. In the dialog that appears next, enter the information required to connect to the database. Be sure to remember the datasource name (DSN) you assign, because it is necessary for the IDC script. Click OK to return to the System Data Sources dialog. Click OK to return to the ODBC administrator and exit the application.

Creating the IDC Script File

Next, you'll set up an IDC script to use in querying the database. The script consists of database logon information, the name of the output template file, and a SQL statement to be executed. Listing 5.3 shows the IDC script I used to create this example. This file is provided on the CD-ROM included with this book; the filename is view.idc.


Listing 5.3. The IDC script for querying the demo request database.

Datasource: Web SQL

Username: sa

Template: view.htx

SQLStatement:

+SELECT FirstName, LastName, Company, Address,

+City, State, Postal, Phone, EMail, ReqID

+FROM DemoRequests


The first line specifies the DSN for the ODBC datasource I created. The second line is the logon user name. This datasource points to a Microsoft Access database that has no security specified. If you are using a secured database, you can also use Password: to specify the logon password.

The third line in the script specifies the output template file to be used. This is a specially formatted HTML file that contains placeholders for the database fields returned by the query as well as other information available from the IDC itself. (This file is discussed in the next section.)

The next several lines provide the SQL statement to be executed whenever the script is loaded by the IIS Web server. You can specify just about any type of SQL statement as long as it's valid for the database type and structure you're using. Here, you're selecting several fields from a table named DemoRequests. You can have the SQL statement span multiple lines by placing a plus sign (+) at the start of the new line.

Creating the Output Template File

This section discusses the meat of this example: the output template file. Listing 5.4 presents the contents of this file; it is included on the CD-ROM as view.htx.


Listing 5.4. The output template for the demo request display page.

<html><title>Example Database Connection</title>

<BODY BGCOLOR="FFFFFF">

<font size=2>

<h1>These are the folks in the database:</h1>

<h2>Click the Details button for more details:</h2>

<CENTER><TABLE border=1>

<tr>

<%begindetail%>

<TD>

Name: <b><%FirstName%> <%LastName%></b><br>

Company: <b><%Company%></b><br></TD>

<TD>

<OBJECT ID="cmdDetails<%ReqID%>" WIDTH=96 HEIGHT=32

 CLASSID="CLSID:D7053240-CE69-11CD-A777-00DD01143C57">

    <PARAM NAME="Caption" VALUE="Details">

    <PARAM NAME="Size" VALUE="2540;846">

    <PARAM NAME="FontCharSet" VALUE="0">

    <PARAM NAME="FontPitchAndFamily" VALUE="2">

    <PARAM NAME="ParagraphAlign" VALUE="3">

    <PARAM NAME="FontWeight" VALUE="0">

</OBJECT>

<SCRIPT LANGUAGE="VBScript">

<!--

sub cmdDetails<%ReqID%>_click

Dim lTemp

lTemp = "Address: " & "<%Address%>" & Chr(13)

lTemp = lTemp & "City/State/Zip: " & "<%City%>, <%State%> <%Postal%>" & chr(13)

lTemp = lTemp & "Phone: " & "<%Phone%>" & chr(13)

lTemp = lTemp & "EMail: " & "<%EMail%>" & chr(13)



MsgBox lTemp, 0, "<%FirstName%> <%LastName%>"



end sub

--></SCRIPT>

</TD></tr>

<%enddetail%>

</table></CENTER></font>

</body></HTML>


The beginning of this file looks like standard HTML. If you look closely, however, you'll see some hybrid HTML tags such as <%begindetail%>, <%FirstName%>, and <%enddetail%>. These are tags interpreted by the IDC when it is returning the output page to the user's Web browser. The <%begindetail%> and <%enddetail%> tags delineate the beginning and end of a section of the file where results from the SQL query will be placed. The HTML that appears between these two tags is repeated for each record returned by the SQL SELECT statement. Tags such as <%FirstName%> and <%LastName%> are the field names returned by the SQL SELECT statement contained in the IDC script. (Refer to Listing 5.3.)

All the details are displayed using an HTML table with two columns. The first column displays the name and company returned from the query. This is done by using these lines:


<TD>

Name: <b><%FirstName%> <%LastName%></b><br>

Company: <b><%Company%></b><br></TD>

The second column is where you start to see some VBScript creep onto the scene. First, you see the insertion of an ActiveX command button:


<OBJECT ID="cmdDetails<%ReqID%>" WIDTH=96 HEIGHT=32

 CLASSID="CLSID:D7053240-CE69-11CD-A777-00DD01143C57">

Notice the ID property; it includes one of the fields returned in the IDC script (ReqID). Because VBScript does not allow for control arrays, the template must generate a unique name for each ActiveX control to be placed in the output page. Because the ReqID field is the unique primary key in the table, it's an appropriate field to use. The IDC replaces the text <%ReqID%> with the field's value each time a record is output using the template.

After the object's definition comes some VBScript code for its Click event. Notice again that <%ReqID%> appears in the control's name. The event procedure uses more of the fields from the query to create a string. This string then is displayed using the MsgBox statement.

Finally, you come to the end of the table's row and the <%enddetail%> tag. Then the closing HTML tags appear, and the </HTML> tag ends the template.

Viewing the Results

This template produces a very compact listing of the records returned from the database. If more detail about a particular record is needed, the user can click the Details button to display the message box containing those additional details.

To view the results, enter the URL to the IDC script file into Internet Explorer's address box and press Enter. After the IDC churns a minute or so (depending on the size of the database being accessed), the results page appears. Figure 5.4 shows the results for a sample database on my Web server. Figure 5.5 shows the message displayed for Dilbert Bates after I click his Details button.

Figure 5.4 : The page resulting from the IDC script.

Figure 5.5 : The message box created using VBScript.

Listing 5.5 shows the HTML generated by the IDC. You can compare this listing with Listing 5.4 to determine that the IDC has indeed properly embedded the SQL query results into the template file and the VBScript code. Listing 5.5 is included on the CD-ROM as view.htm.


Listing 5.5. The HTML source for the IDC-generated page.

<html>

<title>Example Database Connection</title>

<BODY BGCOLOR="FFFFFF">

<font size=2>

<h1>These are the folks in the database:</h1>

<h2>(Click the Details button for more details)</h2>

<CENTER><TABLE border=1>



<TR><TD>

Name: <b>Jim Smith</b><br>

Company: <b>Smith and Sons Publishing</b><br>

</TD><TD>

    <SCRIPT LANGUAGE="VBScript">

<!--

sub cmdDetails825961365_click

Dim lTemp

lTemp = "Address: " & "123 Book Way" & Chr(13)

lTemp = lTemp & "City/State/Zip: " & "New York, NY 10001" & chr(13)

lTemp = lTemp & "Phone: " & "212-555-1212" & chr(13)

lTemp = lTemp & "EMail: " & "" & chr(13)



MsgBox lTemp, 0, "Jim Smith"



end sub

--></SCRIPT>

<OBJECT ID="cmdDetails825961365" WIDTH=96 HEIGHT=32

 CLASSID="CLSID:D7053240-CE69-11CD-A777-00DD01143C57">

    <PARAM NAME="Caption" VALUE="Details">

    <PARAM NAME="Size" VALUE="2540;846">

    <PARAM NAME="FontCharSet" VALUE="0">

    <PARAM NAME="FontPitchAndFamily" VALUE="2">

    <PARAM NAME="ParagraphAlign" VALUE="3">

    <PARAM NAME="FontWeight" VALUE="0">

</OBJECT>

</TD></tr>



<tr><TD>

Name: <b>Carlos Espinoza</b><br>

Company: <b></b><br>

</TD><TD>

    <SCRIPT LANGUAGE="VBScript">

<!--

sub cmdDetails826028414_click

Dim lTemp

lTemp = "Address: " & "Route 102 Box 12" & Chr(13)

lTemp = lTemp & "City/State/Zip: " & "Panama City, Panama" & chr(13)

lTemp = lTemp & "Phone: " & "" & chr(13)

lTemp = lTemp & "EMail: " & "esp@panama.net" & chr(13)



MsgBox lTemp, 0, "Carlos Espinoza"



end sub

--></SCRIPT>

<OBJECT ID="cmdDetails826028414" WIDTH=96 HEIGHT=32

 CLASSID="CLSID:D7053240-CE69-11CD-A777-00DD01143C57">

    <PARAM NAME="Caption" VALUE="Details">

    <PARAM NAME="Size" VALUE="2540;846">

    <PARAM NAME="FontCharSet" VALUE="0">

    <PARAM NAME="FontPitchAndFamily" VALUE="2">

    <PARAM NAME="ParagraphAlign" VALUE="3">

    <PARAM NAME="FontWeight" VALUE="0">

</OBJECT>

</TD></tr>



<TR><TD>

Name: <b>Dilbert Bates</b><br>

Company: <b>Bates Shower Repair</b><br>

</TD><TD>

    <SCRIPT LANGUAGE="VBScript">

<!--

sub cmdDetails825961369_click

Dim lTemp

lTemp = "Address: " & "123 Hotel Drive" & Chr(13)

lTemp = lTemp & "City/State/Zip: " & "New York, NY 10001" & chr(13)

lTemp = lTemp & "Phone: " & "212-555-1234" & chr(13)

lTemp = lTemp & "EMail: " & "bates@shower.com" & chr(13)



MsgBox lTemp, 0, "Dilbert Bates"



end sub

--></SCRIPT>

<OBJECT ID="cmdDetails825961369" WIDTH=96 HEIGHT=32

 CLASSID="CLSID:D7053240-CE69-11CD-A777-00DD01143C57">

    <PARAM NAME="Caption" VALUE="Details">

    <PARAM NAME="Size" VALUE="2540;846">

    <PARAM NAME="FontCharSet" VALUE="0">

    <PARAM NAME="FontPitchAndFamily" VALUE="2">

    <PARAM NAME="ParagraphAlign" VALUE="3">

    <PARAM NAME="FontWeight" VALUE="0">

</OBJECT>

</TD></tr>



</table></CENTER></font>

</body></HTML>


Review

This chapter discussed several ways to combine VBScript and HTML. Although the examples weren't earth-shattering, they did demonstrate the basics needed to fully integrate VBScript with your Web pages, your server-side applications, and your existing databases you want to publish on your Web site.

Part II of this book, "Objects in VBScript," examines embedding ActiveX controls and other objects into your Web pages and VBScript code. You'll begin by looking at document objects in Chapter 6 "The Scripting Model."