Web Programming Unleashed
VBScript Application Pages
by Keith Brophy and Tim Koets
- Metric Conversion Application
- Interactive Tutorial Application
- Pace-Pal Application
- Information Submittal Application
- Browser Objects
In Chapter 22, "The VBScript Language," you learned
the language mechanics of VBScript. This chapter shows VBScript
in action and puts those techniques to use. The samples that follow
encompass a spectrum of uses ranging from pages that calculate
running pace per mile on the user's local PC to pages that perform
front-end validation before submitting orders to a server. Keep
in mind, however, that even though these samples cover a lot of
ground, they just touch the surface of VBScript's potential. Because
VBScript is a full-fledged language that lets you build programs
around any object you want to incorporate, the only real limit
to the type of solutions you can implement is your own creativity.
As you study the samples in this chapter, you will see how to
assemble the capabilities of this language into a comprehensive
program and perhaps develop a sense of VBScript's range of possibilities.
For more details on many facets of VBScript, see the Sams.net book Teach Yourself VBScript in 21 Days; it includes more sample programs with comprehensive discussions of each technique
The Metric Converter application page is a good example of relatively simple code that still accomplishes a very useful function for the user. This application converts a distance specified on the page in feet and inches into the corresponding metric equivalent. Figure 23.1 shows the implementation of this code on the corresponding page.
This sample page is contained in the file meters.htm on this book's CD-ROM. I recommend that you access this page by starting with the main index page to VBScript samples, VBSDemo.htm
This page is built around a primary conversion function. User input supplied on the page through text input boxes is passed as parameter data to the function call in the VBScript call. This core function is shown in the following code:
Function ConvertToMeters(ByVal Inches, Feet) Inches = Feet * 12 + Inches ConvertToMeters = Inches * 0.0254 End Function
Standard VBScript mathematical operators carry out the conversion. Then, the function returns the conversion result to the calling code by setting the result equal to the name of the function itself, ConvertToMeters. The calling code displays the result to the user by updating a text box on the Web page.
The code listing for the entire Web page is shown in Listing 23.1.
Listing 23.1. The Metric Converter Web page code.
<HTML> <HEAD> <TITLE>The Metric Converter</TITLE> </HEAD> <BODY> <H1><A HREF="http://www.mcp.com"><IMG ALIGN=BOTTOM SRC="../shared/jpg/samsnet.jpg" BORDER=2></A> The Metric Converter</H1> <HR> <CENTER><H2>Passing variables both by value and by reference into a procedure</H2> <P>Enter a distance in inches and feet and click on the "Convert" button. The result will be displayed in meters. <PRE><INPUT NAME="txtFeet" SIZE=10 > feet <INPUT NAME="txtInches" SIZE=10 > inches</PRE> <P><INPUT TYPE="BUTTON" NAME="cmdConvert" VALUE="Convert"> <P><INPUT NAME="txtResult" SIZE=50 ></CENTER> <HR> <center> from <em>Teach Yourself VBScript in 21 Days</em> by <A HREF="../shared/keith.htm">Keith Brophy</A> and <A HREF="../shared/tim.htm">Tim Koets</A><br> Return to <a href="..\default.htm">Content Overview</A><br> Copyright 1996 by SamsNet<br> </center> <SCRIPT LANGUAGE="VBScript"> <!-- Option Explicit Sub cmdConvert_OnClick() Dim Inches, Feet, Meters Inches = txtInches.Value Feet = txtFeet.Value Meters = ConvertToMeters(Inches, Feet) txtResult.Value = "There are " & Meters & " meters in " & Feet & " feet and " & Inches & " inches." End Sub Function ConvertToMeters(ByVal Inches, Feet) Inches = Feet * 12 + Inches ConvertToMeters = Inches * 0.0254 End Function --> </SCRIPT> </BODY> </HTML>
As you can see from Figure 23.1, the user simply enters the number of inches and feet in the appropriate text boxes and clicks the Convert button. That action calls the function ConvertToMeters, which converts the values into meters and returns the value. The value is then displayed in the result text box on the Web page. The entire conversion process is carried out without requiring any server-side interaction.
A tutorial program called the VBScript ActiveX Tutorial demonstrates how you can use the label control to give your users a high degree of feedback during their interaction with your scripts.
This tutorial uses standard HTML code to display a series of questions
on the screen. Next to each question is a standard input text
control to collect the answer. To the right of the text control
is a column of hints, displayed with the label control. All question-related
information is presented within an HTML table to help align the
columns of information.
The tutorial is available on the CD-ROM in the file interact.htm.
The user interacts with this program by entering his or her responses in the appropriate text boxes and then pressing the Provide Feedback command button. This button triggers script code that evaluates each answer. If an answer is correct, a green label displays "Correct!" If an answer is incorrect, a red label provides the correct answer. To provide a high degree of visual cue feedback, a correct answer changes the angle of the feedback label to point slightly upward with a jaunty air. If an answer is incorrect, the feedback label angle changes to droop slightly downward. A label at the bottom of the feedback area shows the total number of correct answers. Figure 23.2 shows the feedback label's response to both correct and incorrect answers.
The degree to which the feedback of this program impresses you probably depends on your background. If you're coming to VBScript from a traditional programming background, you might think, "This interactivity is very much like what I can already do with a Windows program." If you're approaching VBScript from a heavy Web page development background, you might be thinking, "This really lets me do a lot more than I ever could before in my Web pages." Both of these perspectives are accurate. VBScript integrates controls and provides programmability much like its parent product, Visual Basic, has for some time in the Windows environment. VBScript now extends this power to the Web page.
Listing 23.2 shows the code that assesses the answers to the tutorial questions and provides the feedback. A comparison is performed on each text box answer. For the sake of the example, the comparison is very simple. In an actual tutorial, you would probably perform much more extensive comparisons, converting the response to uppercase, checking for close variations on the correct answer, and so on. With this sample program, if an exact match occurs on the answer, it is considered a correct response.
Listing 23.2. Providing feedback based on responses.
<SCRIPT LANGUAGE="VBSCRIPT"> <!-- Sub cmdFeedback_OnClick 'This routine is called when the user clicks the feedback button. dim Correct Correct = 0 ' Change all feedback labels to italic rather than bold lblFeedback1.fontbold = 0 lblFeedback1.fontitalic = 1 lblFeedback2.fontbold = 0 lblFeedback2.fontitalic = 1 lblFeedback3.fontbold = 0 lblFeedback3.fontitalic = 1 ' Assess Question 1 if txtQuestion1.Value = "<OBJECT>" then ' Correct response Correct = Correct + 1 lblFeedback1.angle = "10" lblFeedback1.fontsize = "24" lblFeedback1.caption = "Correct!" lblFeedback1.ForeColor = "65280" else ' Incorrect response lblFeedback1.angle = "350" lblFeedback1.caption = "The <OBJECT> tag" lblFeedback1.ForeColor = "255" end if ' Assess Question 2 if txtQuestion2.Value = "<PARAM>" then ' Correct response Correct = Correct + 1 lblFeedback2.angle = "10" lblFeedback2.fontsize = "24" lblFeedback2.caption = "Correct!" lblFeedback2.ForeColor = "65280" else ' Incorrect response lblFeedback2.angle = "350" lblFeedback2.caption = "The <PARAM> tag" lblFeedback2.ForeColor = "255" end if ' Assess Question 3 if txtQuestion3.Value = "ID" then ' Correct response Correct = Correct + 1 lblFeedback3.angle = "10" lblFeedback3.fontsize = "24" lblFeedback3.caption = "Correct!" lblFeedback3.ForeColor = "65280" else ' Incorrect response lblFeedback3.angle = "350" lblFeedback3.caption = "The ID attribute" lblFeedback3.ForeColor = "255" end if ' Show the results lblResults.caption = cstr(Correct) & " out of 3 correct!" end sub --> </SCRIPT>
When the user gives a correct response, the label angle, caption, font size, and ForeColor are all adjusted accordingly. Likewise, if an answer is incorrect, the angle, caption, and ForeColor are adjusted for incorrect response feedback. The lblResults label that is updated in the last line of the script illustrates a particularly useful technique. You can make a response appear at just the right moment. The lblResults label does not initially appear to the user because the following parameter is used to declare the starting object caption:
<param name="caption" value="">
When you want a caption to appear, you simply assign one in your
code, and presto! The user sees text where there was none before.
This program uses many labels-four to be exact-to provide a dynamic
page that updates with user feedback. In the old Web programming
model, you probably would have needed at least two Web pages,
one of them custom-generated by a CGI script on the server, to
produce the equivalent function. The simple addition of the label
control and VBScript enable you to integrate all this feedback
into one relatively simple page.
A rather interesting behavior occurs with early beta versions of the label control if you don't include any parameter tag for the caption in your object declaration. When the label is drawn on screen, it appears with the caption "Default"! You can still assign values to properties even if they are not declared with the parameter tag in an object declaration. You can change the caption at some point in your program if you start with this default caption. However, if you don't want to generate a caption until some interaction with your program occurs, you would prefer that your user see nothing for the label, rather than the confusing "Default" on screen. Setting the parameter equal to the empty string, as defined previously, solves this problem.
Pace-Pal is the running-pace calculation program shown in Figure 23.3. This program resembles other VBScript page applications in that it consists of a standard HTML Web page with embedded VBScript. Pace-Pal allows the user to specify a distance in either miles or kilometers, and a time in minutes/seconds format. (Hours can also optionally be entered if the user has run a distance that takes them that long to cover!) With this information, a runner can calculate his pace per mile. For example, if someone ran a 6.2 mile race (10k) in 37 minutes and 12 seconds and supplied that information to Pace-Pal, Pace-Pal would calculate that the runner averaged a 6-minute mile.
The Pace-Pal program is available on the CD-ROM in the file PacePal.htm.
The Pace-Pal application performs a rather lengthy series of conversions and calculations to derive the pace per mile from the user-supplied input. The Calculation button click event handler, Calc_OnClick, uses underlying functions to carry out these computations. The code for this event appears in Listing 23.3.
Listing 23.3. Calc_OnClick event handler.
Sub Calc_OnClick ' Processes request to calculate pace '-------------------------------------------------------------------------- Dim sngDistanceMiles ' How far was the distance in miles Dim sngDistanceKilos ' How far was the distance in kilos Dim iDuration ' How long did it take Dim iHoursPos ' What position is ":" for hours located at Dim iMinPos ' What position is ":" for minutes located at Dim iSecPos ' What position is ":" for seconds located at Dim sTemp ' Temp holder for user input if (len(document.frmPace.txtDistance.Value) = 0) or _ (len(document.frmPace.txtTime.Value) = 0) then msgbox "A valid time and distance is required!",0,"More Data Required" exit sub end if ' Convert user string to time in seconds sTemp = document.frmPace.txtTime.Value ' iDuration = ConvertStringtoTotalSeconds(sTemp) iDuration = ConvertStringToTotalSeconds(sTemp) ' Divide time by distance ' Convert units if needed If sCurrentUnits = "Kilos" Then sngDistanceKilos = CSng(document.frmPace.txtDistance.Value) ' Convert kilos to miles sngDistanceMiles = sngDistanceKilos * 0.62 Else sngDistanceMiles = CSng(document.frmPace.txtDistance.Value) ' Convert miles to kilos sngDistanceKilos = sngDistanceMiles * 1.613 End If ' Determine pace per unit ' Derive the average pace per mile iSecPerUnit = Int(iDuration / sngDistanceMiles) ' Convert pace in total seconds to formatted pace string showing minutes/seconds document.frmPace.lblPaceMiles.Caption = ConvertSecondsToString(iSecPerUnit) ' Derive the average pace per kilo iSecPerUnit = Int(iDuration / sngDistanceKilos) ' Convert pace in total seconds to formatted pace string ' showing minutes/seconds document.frmpace.lblPaceKilos.Caption = ConvertSecondsToString(iSecPerUnit) End Sub ' Calc_OnClick
The function ConvertStringToTotalSeconds is called to put the original user input string into a calculation-ready numeric format of total seconds. Calculations are then performed using the data in this format. Once a final pace in seconds has been derived from the calculations, the result must be returned to the user. The function ConvertSecondsToString is called to transform the seconds-only data into a more readable minutes-seconds form before it is updated on the page for the user to see. Both of these functions are user-defined functions that are also defined in the VBScript code of the Web page. Listing 23.4 shows the logic for ConvertStringToTotalSeconds.
Listing 23.4. ConvertStringToTotalSeconds function.
Function ConvertStringToTotalSeconds (ByVal sDuration) '-------------------------------------------------------------------------- ' Takes HH:MM:SS format string and converts to total seconds ' When error occurs, continue with next statement rather than halting program on error resume next Dim iPosition 'Position of ":" seperator Dim vHours ' Number of hours required Dim vMinutes ' Number of minutes required Dim vSeconds ' Number of seconds required 'Start working from right of string, parsing seconds sMode = "Seconds" ' Get leftmost time component iPosition = InStr(sDuration, ":") if iPosition = 0 then ' no more time info, assume time info just in ss format vSeconds = sDuration else ' more time info is on string ' store first portion in hours for now, assume hh:mm:ss format vhours = left(sDuration,iPosition - 1) ' Parse string for further processing sDuration = right(sDuration, len(sDuration) - iPosition) ' Get middle time component iPosition = InStr(sDuration, ":") if iPosition = 0 then ' no more time info, must just be mm:ss format vMinutes = vHours vSeconds = sDuration vHours = 0 else ' time info must be in hh:mm:ss format vminutes = left(sDuration,iPosition - 1) seconds = right(sDuration, len(sDuration) - iPosition) end if end if ' Represent all components in terms of seconds vHours = vHours * 3600 vMinutes = vMinutes * 60 ' Return total seconds value ConvertStringtoTotalSeconds = CInt(vHours) + CInt(vMinutes) + CInt(vSeconds) if err.number <> 0 then msgbox "Error #:" & err.number & " Description:" & err.description _ & " Source:" & err.source, 0, "Error in ConvertStringtoTotalSeconds!" end if End Function ' ConvertStringtoTotalSeconds
This sample program illustrates that you can build a rather sophisticated program directly into a Web page's script code. The modular use of functions and good comments helps to keep your code manageable. Some rules of thumb that have been published about scripting suggest that a page should never contain "a lot" of script code. This line of reasoning maintains that if a program has more than a few lines, it should be bundled in a separate Java applet or ActiveX control that's included with the page, rather than as a script that is part of the page itself.
A program such as Pace-Pal refutes this argument. It is very easy to implement in VBScript and was developed in a much shorter time frame than the alternative approaches. If you have a substantial programming task that could be implemented in script or as a control, consider factors such as time, maintenance, and development effort; then base your decision on the circumstances.
So far, the applications presented have focused solely on the scripts that relate to the page running on the client computer without much regard for the Web server. The server has another role that goes beyond just downloading pages or components. In many cases, VBScript code in a page can affect what happens on the server.
At first glance, VBScript might appear to be a periphery player in the server-side communication. After all, many of the pages that a server downloads to a client computer serve simply as front ends for collecting data. However, VBScript can serve as the basis of the front end for data validation and final submittal of the data to the server to ensure clean data and thereby enhance server performance.
For some time, HTML has had a model for collecting data on a page and submitting it to a server. Although that model is evolving with the help of technologies such as VBScript, the concepts are still much the same. Input control fields collect data from the user. Two specific HTML definitions are required for the page to submit that data to a program on the server. The input controls must be defined within a form so that the data from them can be submitted as one data set. Some specific action must trigger the submittal, which is accomplished through an input control that resembles a regular command button but has a type of submit.
Consider the form definition further. When the data is provided to the server, the server must be able to tell which program to submit that data to. After all, the server can't just assume the data should be added to a database or saved in a file or ignored. Therefore, the form tag has an ACTION attribute, which specifies the program on the server that processes the input from the client. (These server-side programs that process page data are sometimes called server scripts.) In addition, the form tag definition sets a method attribute to indicate how the information should be passed from the client back to the server.
The full details of this interaction are beyond the scope of this
section, but you should understand some of the technologies involved.
In the past, the primary protocol for supplying data back to the
server and launching a script was CGI, or Common Gateway Interface.
CGI is still in broad use today. In addition, other technologies
such as Internet Server Application Program Interface (ISAPI)
and Internet Database Connectivity (IDC) have emerged. An ISAPI-launched
program on a Windows NT server works in the same address space
as server software, which means that it can be significantly faster
than a traditional CGI server script. The related technology of
IDC can even result in direct database interaction through the
use of a template file.
You can also use VBScript directly on NT Server with the Internet Information Server Web server software. The focus of this section is illustrating the use of VBScript at the browser level, so I do not consider this topic in detail. However, the same VBScript core syntax rules and language fundamentals covered here apply in the server environment as well
Although technical differences exist in the way these approaches are implemented, the concept is the same from the standpoint of your page and your script code. When the user clicks a Submit button on the form, the browser submits all the input fields on the form as well as the action parameter to the server. The server activates the specified application and provides the field names from the form and their associated data as well.
The application is responsible for responding to the request. Typically, the CGI or ISAPI application on the server might store the information from the page into a database. It might also generate another page to download to the client. These tasks are accomplished with assistance from the Web server. Typically, the CGI or ISAPI application generates one long string for a page. This string contains all the tags that make up the Web page to be sent to the client. The server takes care of passing that data through the HTTP protocol back to the client. All this interaction is fairly transparent to the user. From the perspective of the end user, she supplies some data, submits it, and suddenly another page appears.
An example can help illustrate the process and also show the specific way that VBScript comes into play as a front-end validator. Listing 23.5 shows a simple form definition on a page.
Listing 23.5. Form definition.
<form name="frmOrder" action="/scripts/oleisapi.dll/Order.clsOrder.ProcessOrder" method="POST"> Your Name: <input name="txtName"> Street Address: <input name="txtAddress" > City: <input name="txtCity"> State: <input name="txtState"> Zip: <input name="txtZip"> <input type="submit" name="cmdOrder" value="Submit Order"> </form>
Usually, the data in the form would be presented in a more visually attractive format, such as with each element placed in the cell of an HTML table. For the sake of simplicity, the example is shown without any frills
Note that a Submit button is defined at the bottom of the form. When the user selects the Submit button, the browser automatically submits the form to the server. No VBScript code or any kind of code is required to make this happen! This process is part of the HTML form and submit element definition. The server receives data that includes the following string:
Also appended to this string is other information about the contents of txtName, txtAddress, txtCity, txtState, txtZip, and the form method attribute. The string
tells the server to pass this request to the ISAPI OLE automation director, /scripts/oleisapi. (OLE automation is a special method of communicating that some applications, including those generated by Visual Basic 4.0, can respond to.)
Oleisapi is actually a dynamic link library (DLL) on
the server system. Oleisapi starts the requested program.
It can locate the requested program because it is registered in
the system registration database as an OLE automation server.
Order.clsOrder specifies the DLL name and class of the
program intended to handle this request. ProcessOrder
specifies the method of this program that is initiated. Oleisapi
initiates the Order.clsOrder.ProcessOrder method, passing
it two important parameters. The first is the data from the Web
page in one long string. The second parameter is used by Order.clsOrder
to supply a return page that oleisapi directs back to
the server and subsequently back to the client.
This discussion of server-side software focuses on an NT Server Web server solution and the OLEISAPI technology, but the general concepts largely apply to other server environments as well
Listing 23.6 shows the code for the Order.clsOrder.ProcessOrder method. This sample is Visual Basic 4.0 code, not VBScript. It is shown here because it gives you a good, representative idea of what a server-side application might do with data from a Web page.
Listing 23.6. Server application called in response to page form submittal.
Public Sub ProcessOrder(strRequest as String, strResponse as String) Dim strName as String ' Extract the name from the data that came from the page strName = GetNameField (strRequest) ' See if a valid name was supplied if len(strName) = 0 then ' Name is missing, can't process the order. ' Generate a page scolding the user strResponse = <html><head><h1>The name is missing!</h1>" & _ </head><body><p>Please supply a valid name with the order!" & _ </body></html>" else ' Store order info from page in database StoreInDB (strRequest) ' Generate a page confirming to the user strResponse = <html><head><h1>Order Confirmation</h1>" & _ </head><body><p>Thanks for placing the order with us!" & _ </body></html>" end if 'Add the standard header that is needed when sending new page from ' the server to the browser to the front of the response string strResponse = "Content-Type: text/html" & vbCrLf & vbCrLf & strResponse End Sub
The comments in this code segment provide a pretty good overview of what the code is doing. The code calls a user-defined procedure to return only the name field from all the string information that originated from the page. It makes a check to see if a name was supplied. If the name is missing, the code assigns to a string a series of HTML tags that make up the new pages. If the name is present, the order is stored in the database by calling a user-defined procedure. The page is built in a string with HTML tags thanking the user. Then the code adds a required header to the response string to indicate that HTML text format data is returned. The ProcessOrder method procedure then terminates, and the server returns the response string to the client. The client receives the new page, which came from an application-generated string rather than from a file. Of course, the end users don't realize the difference; they just see that a result page has arrived from their original query.
Consider the flow of this interaction when the user forgets to supply a name while specifying an order on the original Web page, as illustrated in Figure 23.4.
The request went all the way to the server, which then detected the missing name, so no data was saved. The response page went back to the user. That's too much overhead for what was accomplished considering that nothing was saved in the database. The interaction involved the user's time, network communication, and server processing time, all for the end result of no change to the server database.
Now, you can finally see an alternative implementation where VBScript comes to the rescue! Suppose that you define exactly the same form, but you add a block of script code to the page, as shown in Listing 23.7.
Listing 23.7. VBScript page-resident validation.
<script language="VBScript"> <!-- function frmOrder_OnSubmit ' Submit order if the request is valid ' Make sure user has supplied name before submitting order to server if len(document.frmOrder.txtName) = 0 then ' No name was supplied, order won't be submitted MsgBox "You must supply a name.",vbOKOnly, "Can't submit order" ' Cancel the submittal frmOrder_OnSubmit = False else ' Order OK, submit it to server MsgBox "Order was submitted. Thanks.",vbOKOnly, "Confirmation" ' Submit the order frmOrder_OnSubmit = True end if end sub --> </script>
The Submit program is available on the CD-ROM in the file Submit.htm. Note that the Submit program is provided only as a client-side sample. The full submittal process does not work unless you provide your own server-side application to receive the input from the client VBScript page
The comments in this code once again provide pretty full details about what transpires. If the text box string has a length of 0, no submittal takes place. How is that accomplished? You simply return a false for the form's OnSubmit event handler. If you had no VBScript event handler, the browser would submit all data automatically. If you supply code for the OnSubmit event of a form, the data is not submitted if the VBScript code returns a false for the event. It will be submitted if the script returns a true for the event. You can see the use of this method in the Else branch of the conditional statement. If the name is present, the data is submitted. Once the form is submitted, the server application that was described earlier will be launched on the server to carry out further processing.
On the form for this example the cmdOrder button was declared to be a special HTML Submit button, by setting its type to TYPE=SUBMIT in the <INPUT> tag. If no event handler was defined, then the form would be automatically submitted when the user clicked on the button. When a form submit event handler is defined, that will be called first.
The event handler is declared by creating the function named "yourform_OnSubmit". This function name is made up of the form name followed by an underscore and then the predefined "OnSubmit" syntax. There is another way to name the event handler, however. You could also plug your own routine into the form tag and associate it with the OnSubmit event:
<FORM ID="YourForm" LANGUAGE="VBScript" OnSubmit="YourVBFunction" ACTION="serversidescript">
Both approaches accomplish the same end result. Your function would do the validation and return a true if the submit was to proceed or false if it wasn't.
However you implement the solution, validation provides great advantages. The code has done something very significant: It has eliminated the need for any server-side validation. The Visual Basic code that stores data in the database no longer needs to check whether a name exists. It is only called if valid data was first verified by the VBScript code that resides at the client computer. This approach saves processing time on the server when the data is saved. You use fewer lines for error-checking code. Better yet, consider what happens when an error does occur. Before, you had communication between the client to the server, processing on the server, and communication from the server to the client just to generate an error message to the user. Now, the client-side processing by VBScript generates the error message directly. VBScript completely eliminates all the network traffic, not to mention the user wait for the network and the server-side processing!
Figure 23.5 shows the flow for this interaction. Compare Figures 23.5 and 23.4, and observe the difference in approaches. This very simple, scaled-down example shows the advantages of placing the validation load on VBScript rather than on the server. Even this simple example shows significant savings.
As you can see, even though VBScript performs the processing on the client, it can have a close association with any programs on the server that might process data from the page. VBScript can execute front-end validation processing before form data is submitted to the server. It can screen out bad data or modify questionable data before submitting it to the server. The front-end processing reduces server load, network load, and even user wait time in the event that the data is bad and an error response must be generated for the user. VBScript can provide feedback right away without the server program generating a response and sending it back.
Of course, when you develop software in this manner, you must plan the scripts in conjunction with the server-side software. You don't gain much by having a script validate data if it's not validating the data according to the right rules. Generally, this kind of in-sync planning of server application and script works out well because the server application must be planned in concert with the form anyway. VBScript can generate smoother performance from the entire server when you use it to perform the type of validation described here.
Most examples presented so far have focused on core capabilities of the VBScript language. For example, the VBScript interpreter directly supports language keywords such as if and dim. This language is consistent whether you use VBScript hosted in the Internet Explorer browser, in some other browser, in the Internet server, or even in some application that supports VBScript not related to the Web at all.
Other examples looked at objects defined externally to the browser, including ActiveX controls. The host environment enables VBScript to control objects. Support in the Internet Explorer browser and its interface with the VBScript interpreter lays the framework for your VBScript to access such objects. If you use VBScript in another host environment, such as a different browser or a non-Web-related application, it may very well provide the same support. On the other hand, it may not. The VBScript language definition does not require every host to provide this capability. Clearly, the host environment makes a difference in what you can do with VBScript.
You still need to consider one more area: objects the host itself exposes. The Internet Explorer, which is the host I focus on, provides VBScript with access to information about itself and with interfaces to control its own behavior through objects such as the document object.
Objects exposed by the Internet Explore browser include the window object, the document object, the element object, the frame object, the history object, the script object, the anchor object, the element object, the form object, and the navigator object. With these objects you can do many things. From your code, you can link to other pages. You can detect the version of the browser that is used. You can respond to mouse movements and clicks on link areas. You can work with the browser history list. You can even find out the name of the referring page for the current page. In other words, you can tell the page that your user visited before he or she linked to the page that contains your VBScript. You can also use these objects to provide control over multiple frames from your code. This script statement, for example, could reside in a script in a currently displayed frame page and update the contents of another visible frame:
parent.frames(1).document.writeln "<HTML><BODY><h2> You can " & "generate HTML to a page!</h2></BODY></HTML>" parent.frames(1).document.close
A frame is an independent HTML window created through the <FRAMESET> and <FRAME> tags. You can find more details on frames from any HTML reference. Frames can be referenced in VBScript through the objects and properties exposed by the browser. The parent keyword references the parent window of the current frame. That window contains a collection of all existing frames created underneath it. The first is referenced as parent.frames(0) and the second as parent.frames(1). The document keyword indicates the document object belonging to that frame. Writeln is a method of the document object that you can use to generate HTML content to a page, and close is a method used to conclude the document changes.
The possibilities are limitless. A good representative summary of these intrinsic browser objects appears in the sample program Browser.htm on the CD-ROM. This page includes samples of script control between frames, various ways to advance from one page to another, and methods to determine information ranging from the browser version to the last date that a page changed. You can inspect the source code to observe the various techniques used. A table of some of the key properties and methods of the browser objects appears on this page. Browser.htm serves as a good initial reference point to the browser objects for you. A detailed discussion of all the objects would be very lengthy given the range of capabilities. Refer to Microsoft's documentation for the comprehensive documentation. However, the samples you can inspect in Browser.htm should be enough to get your script-creation efforts off to a good start.
As the samples in this chapter demonstrate, VBScript has very few limitations. You saw several examples of the types of page-resident application solutions that VBScript can provide. For example, one application carried out a simple metric conversion, using very little code. Another sample demonstrated an interactive tutorial that provides user question-and-answer feedback through an ActiveX label control with no server-side intervention. You saw a script that uses a more complex series of calculations in the Pace-Pal running-calculator program, as well as a sample of how to use front-end techniques for validating data before submitting it to a server. Finally, you examined an application that addressed a broad range of capabilities for interacting with browser objects. Separating hype from reality in the rapidly evolving Internet technology arena is not easy, but the examples here underscore the fact that VBScript is the real thing. With some creativity, persistence, and a good knowledge of the capabilities of VBScript, you can deliver quick-to-develop, impressive solutions.