Nancy Winnick Cluts
Developer Technology Engineer
Microsoft Corporation
October 27, 1997
Contents
Introduction
What Scripting Is, and Why and When to Use It
VBScript
JScript
Using Both VBScript and JScript
Server-Side Scripting
Scriptlets
Is Scripting Just for Browsers?
Scripting Resources
In the beginning, there was HTML. And the hordes used HTML to produce Web pages. And they looked at the Web pages, and saw that they were good. But after a time, visitors to the Web sites grew restless and bored with the Web sites. They clamored for more. They wanted the page to interact with them. They wanted dynamic content. The hordes were also restless. They wanted to be able to provide different content in different contexts. Thus, the notion of scripting was born.
Okay, maybe I'm being just a tad dramatic. But it's a lot more poetic than telling you that scripting HTML is like creating a Microsoft Excel macro: You create your spreadsheet data and create a macro to dynamically update rows or columns based on a specified calculation. With scripting, you write your HTML code and create scripts to take action based on user input or variables.
In this article, I am going to talk about what scripting is and why you might want to use it. I'll give you some information about the different scripting languages (Visual Basic® Scripting Edition [VBScript] and JScript) that are available and include examples of scripting. I'll also provide information about server-side scripting and, at the end of this article, a list of links to resources for more information about scripting.
Scripting enables you to set and store variables, and work with data in your HTML code. Many Web sites now employ scripting to check the browser a user is running, validate input, work with applets or controls, and communicate to the user. Let's say that you are creating a Web site that contains a form for ordering ballet tickets. Users can choose the ballet they want to see by entering the title. Now let's say a user types in "Swine Lake." Well, if she were looking for a version starring Miss Piggy, that might be correct, but most ballet companies actually perform "Swan Lake." You could use scripting to validate the name of the ballet and, if the name is not valid, you can display a message box alerting the user to type in a valid name (and even suggest what the correct name might be).
Scripts can be used in harmony with controls or applets, too. In the example above, you could write an applet that gathers the names of the ballets playing during the season and provide that information to the user in a list box. You could use scripting to validate the information once it was chosen or to confirm the order with the user.
Two of the most popular scripting languages today are ECMAScript (formerly known as JavaScript) and VBScript. You can use any scripting language you like as long as your audience's browsers support it. In fact, you can use a combination of scripting in your HTML source code. In the following sections of this article, I will give you more information about VBScript and JScript and provide you with a few examples of each scripting language.
Visual Basic Scripting Edition, also known as VBScript, enables authors to create scripts using a subset of the Microsoft Visual Basic language. If you are already a Visual Basic programmer, or if you are not a programmer but are looking for a scripting language that is easy to learn, VBScript might be the right language for you. VBScript is implemented as a fast, portable interpreter for use in Web browsers and applications that use ActiveX controls, Java applets, and OLE Automation servers.
VBScript is a strict subset of the Visual Basic for Applications language that is used in popular applications such as Microsoft Excel, Microsoft Access, Microsoft Project, and the Visual Basic 4.0 development system. VBScript was designed to be fast, so it does not support the use of strict types -- it only supports the use of Variants. It also must be safe for the World Wide Web, so it does not include functionality that directly accesses the client machine's operating system or file system. For example, you cannot do file I/O or read the registry on the client machine.
VBScript provides support for three separate classes of objects:These examples are all available for testing and viewing from the VBScript Web site in the samples section . I'm showing you only a few of the samples the site has to offer.
Let's start with the classic Hello World example using VBScript. The following code shows you how simple it is to create a button (by using INPUT TYPE=BUTTON) that, when clicked (Sub BtnHello_OnClick), displays a message box (MsgBox) with the text, "Hello, world!":
<CENTER> <P> <H2>Hello, world sample</H2> <INPUT TYPE=BUTTON VALUE="Click me" NAME="BtnHello"> </CENTER> <SCRIPT LANGUAGE="VBScript"> <!-- Sub BtnHello_OnClick MsgBox "Hello, world!", 0, "My first active document" End Sub --> </SCRIPT>
That was pretty simple. Of course, many of us aren't going to use scripting to simply put up a box that says "Hello, world!" Let's move on to a more realistic example.
The Ordering Flowers example demonstrates how you can use VBScript to create a form and gather and validate data given by the user. This form can be used for ordering flowers . It uses radio buttons (INPUT TYPE=RADIO NAME) to enable the user to choose which type of card to include with the flowers, text input fields (INPUT NAME=) to gather information on where to send the flowers, and a button (INPUT TYPE=BUTTON) to submit the request. Here is the HTML source code:
<INPUT TYPE=RADIO NAME=OptOccasion CHECKED> Birthday <INPUT TYPE=RADIO NAME=OptOccasion> Anniversary <INPUT TYPE=RADIO NAME=OptOccasion> Get well soon <FONT SIZE=3> <B>When and where should the flowers be sent?</B> </FONT> <BR> Date <INPUT NAME=TxtDate SIZE=60> Name <INPUT NAME=TxtName SIZE=60> Address <INPUT NAME=TxtAddress SIZE=60> City <INPUT NAME=TxtCity SIZE=60> State <INPUT NAME=TxtState SIZE=60> Zip code <INPUT NAME=TxtZip SIZE=60> <INPUT TYPE=BUTTON VALUE="Submit" NAME="BtnSubmit"> <INPUT TYPE=BUTTON VALUE="Clear" NAME="BtnClear"> <INPUT TYPE=BUTTON VALUE="Init" NAME="BtnInit"><BR>
Now that we have a place to put the information, VBScript code is used to validate the data. The fields are initialized when the window is loaded (Sub Window_OnLoad()) in the BtnInit_OnClick() function.
<SCRIPT LANGUAGE="VBScript"> <!-- Option Explicit Dim strMsgBoxTitle Dim bValidOrder Sub Window_OnLoad strMsgBoxTitle = "MSFTD" Call BtnInit_OnClick End Sub Sub BtnInit_OnClick TxtName.Value = "Joe Smith" TxtAddress.Value = "1 Main Street" TxtCity.Value = "Springfield" TxtState.Value = "Washington" TxtZip.Value = "12345" TxtDate.Value = Date + 3 End Sub
When the user clicks the Submit button, VBScript code is used again to validate the input. In the function BtnSubmit_OnClick(), each text field is checked for valid entry. The function CheckSpecified() checks for non-null entries and that the delivery date is reasonable. If it's not, a message box displays this message: "Not even we can deliver that fast!"
Sub BtnSubmit_OnClick bValidOrder = True Call CheckSpecified(txtName.Value, "Please specify a name.") Call CheckSpecified(txtAddress.Value, "Please specify an address.") Call CheckSpecified(txtCity.Value, "Please specify a city.") Call CheckSpecified(txtState.Value, "Please specify a state.") Call CheckSpecified(txtZip.Value, "Please specify a zip code.") Call CheckSpecified(txtDate.Value, "Please specify a date.") Call ValidateDeliveryDate If bValidOrder Then MsgBox "Thank you for your order!", 0, strMsgBoxTitle ' TODO: Actually send the order. End If End Sub Sub ValidateDeliveryDate Dim SoonestWeCanDeliver Dim RequestedDate If Not bValidOrder Then Exit Sub SoonestWeCanDeliver = Date + 2 RequestedDate = CDate(TxtDate.Value) If RequestedDate < SoonestWeCanDeliver Then bValidOrder = False MsgBox "Not even we can deliver that fast!", 0, strMsgBoxTitle End If End Sub Sub CheckSpecified(ByVal strFieldValue, ByVal strMsg) If strFieldValue = "" And bValidOrder Then MsgBox strMsg, 0, strMsgBoxTitle bValidOrder = False End If End Sub Sub BtnClear_OnClick TxtName.Value = "" TxtAddress.Value = "" TxtCity.Value = "" TxtState.Value = "" TxtZip.Value = "" TxtDate.Value = "" End Sub --> </SCRIPT>
The last VBScript example I will show you is Maintaining State with Cookies . This example shows you how easy it is to save values across Web pages using cookies. Users can click buttons to read a variable, save a variable, remove a variable, read a cookie, and flip Web pages. To use this example, go ahead and click the Save Variable Button. The following VBScript is run:
Sub SetVariable(strVariableName, varVariableValue) Document.Cookie = strVariableName & "=" & varVariableValue End Sub
I am creative, so I picked test as the variable and 1 as the value. Then I clicked the Read Variable button to see that the right variable was set. It was. Then I checked to see if the value was actually saved across Web pages by clicking the Next Page button and clicking Read Variable on that page. The following VBScript reads the variable I entered on the previous page:
Function ReadVariable(strVariableName) 'these five variables are used in the string manipulation 'code that finds the variable in the cookie. Dim intLocation Dim intNameLength Dim intValueLength Dim intNextSemicolon Dim strTemp 'calculate length and location of variable name intNameLength = Len(strVariableName) intLocation = Instr(Document.Cookie, strVariableName) 'check for existence of variable name If intLocation = 0 Then 'variable not found, so it can't be read ReadVariable = NOT_FOUND Else 'get a smaller substring to work with strTemp = Right(Document.Cookie, Len(Document.Cookie) - intLocation + 1) 'check to make sure we found the full string, not just a substring If Mid(strTemp, intNameLength + 1, 1) <> "=" Then 'oops, only found substring, not good enough ReadVariable = NOT_FOUND 'note that this will incorrectly give a not found result if and only if 'a search for a variable whose name is a substring of a preceding 'variable is undertaken. For example, this will fail: ' 'search for: MyVar 'cookie contains: MyVariable=2;MyVar=1 Else 'found full string intNextSemicolon = Instr(strTemp, ";") 'if not found, then we need the last element of the cookie If intNextSemicolon = 0 Then intNextSemicolon = Len(strTemp) + 1 'check for empty variable (Var1=;) If intNextSemicolon = (intNameLength + 2) Then 'variable is empty ReadVariable = "" Else 'calculate value normally intValueLength = intNextSemicolon - intNameLength - 2 ReadVariable = Mid(strTemp, intNameLength + 2, intValueLength) End If End If End if End Function
JScript is Microsoft's implementation of an ECMA-compliant scripting language (like JavaScript) that is targeted specifically to the Internet. Like VBScript, JScript is implemented as a fast, portable interpreter for use in Web browsers and applications that use ActiveX controls, Java applets, and OLE Automation servers. JScript is not Java and has nothing to do with Java. It is closer in syntax to C or C++. If you are a C or C++ developer, you will probably find JScript to be a very easy scripting language to learn (I know I did).
Also like VBScript, JScript supports three separate classes of objects for use within JScript:
You may be confused by the term ECMAScript that I've been using in this article. You're in good company. Here's the deal. ECMA (European Computer Manufacturers Association) is a European-based association for standardizing information and communications systems. The standard recently approved, known as ECMA-262, is based on joint submissions from Microsoft and Netscape. JScript 3.0 is Microsoft's implementation of the new ECMA-262 scripting language. JavaScript is a scripting language written by Netscape that preceded the ECMA standard. There's an excellent introduction to JavaScript available on the Web, if you'd like to read up on it. Basically, when talking about JScript or JavaScript, we are talking about implementations of the same standard scripting language, ECMA -- the implementations are just marketed by different companies.
These examples are available for testing and viewing from the JScript Web site. As with the VBScript examples, I'm showing only a sampling of what they have to offer. You may experience a sense of déjà vu in this section because two of the JScript examples are the same as the VBScript examples. They are a bit different in how they work. I decided to show you examples that show off VBScript and JScript rather than trying to cobble together an example that shows only syntax variation (if I did that, I'd run the risk of showing you either VB-like JScript or C-like VBScript). Let's start with the perennially popular Hello World example.
The Hello World example is the bare-bones JScript example. It provides a button that, when clicked, displays a message box with the text, "Hello, world!"
<CENTER> <P> <H2>Hello, world sample</H2> <FORM Name="Form1" ACTION=""> <INPUT TYPE=BUTTON VALUE="Click me" NAME="BtnHello" OnClick="sayhello()" > </FORM> </CENTER> <SCRIPT LANGUAGE="JavaScript"> <!-- function sayhello () { alert("Hello, world!") } //--> </SCRIPT>
Here again, HTML code is used to set up the button and JScript is used to perform an action (displaying the message box using the alert function) when the button is clicked.
The second Ordering Flowers example demonstrates client-side validation using JScript. As in the VBScript example, this example uses radio buttons to enable the user to choose which type of card to include with the flowers, text input fields to gather information on where to send the flowers, and a button to submit the request. The HTML source code is the same for this example as it is for the VBScript example, so I won't show it here. What is different, however, is the script. The following JScript code is used to do client-side validation:
<SCRIPT LANGUAGE="JavaScript"> <!-- var bValidOrder var f = document.form1 function Init() { var d document.form1.TxtName.value = "Joe Smith" document.form1.TxtAddress.value = "1 Main Street" document.form1.TxtCity.value = "Springfield" document.form1.TxtState.value = "Washington" document.form1.TxtZip.value = "12345" d = new Date() d.setDate(d.getDate() + 3) f.TxtDate.value = (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getYear() } function SubmitOrder() { bValidOrder = true CheckSpecified(f.TxtName.value,"Please specify a name.") CheckSpecified(f.TxtAddress.value,"Please specify an address.") CheckSpecified(f.TxtCity.value,"Please specify a city.") CheckSpecified(f.TxtState.value,"Please specify a state.") CheckSpecified(f.TxtZip.value,"Please specify a zip code.") CheckSpecified(f.TxtDate.value,"Please specify a date.") ValidateDeliveryDate() if (bValidOrder) { alert("Thank you for your order!") // TODO: Actually send the order. } } function ValidateDeliveryDate() { var SoonestWeCanDeliver var RequestedDate var t if (bValidOrder) { SoonestWeCanDeliver = new Date() SoonestWeCanDeliver.setDate(SoonestWeCanDeliver.getDate() + 2) t = Date.parse(f.TxtDate.value) RequestedDate = new Date() RequestedDate.setTime(t) if (RequestedDate.getTime() < SoonestWeCanDeliver.getTime()) { bValidOrder = false alert("Not even we can deliver that fast!") } } } function CheckSpecified(strFieldValue, strMsg) { if (strFieldValue == "") { if (bValidOrder) { alert(strMsg) bValidOrder = false } } } function Clear() { f.TxtName.value = "" f.TxtAddress.value = "" f.TxtCity.value = "" f.TxtState.value = "" f.TxtZip.value = "" f.TxtDate.value = "" } //--> </SCRIPT>
Although there are two different scripting languages, they can peacefully coexist on the same Web page. There's an example on the Internet Explorer Web site that demonstrates a mortgage calculator implemented with VBScript or JScript. Just click the button to choose which script to run and view the source for all of the details. It's interesting to see what code that performs identical tasks looks like in two different languages.
Server-side scripting is scripting done on the server. Well, that's the easy definition. It enables you to run scripts on the server rather than on the client machine. This works well for information that can be stored in a central place (like a database). With server-side scripting, you can enable visitors to your site to have personalized views of the content you offer. The script on the server can conditionally show or not show content that the user has requested, based on information kept in a database on the server.
To implement server-side scripting, you use Active Server Pages (ASP). ASP technology is built directly into Microsoft Web servers. It is supported on Windows NT® running Internet Information Services (IIS) 3.0, Windows NT Workstation 4.0 running Peer Web Services, and Windows® 95 Personal Web Server. If you want to use Active Server Pages with either Personal Web Server on Windows 95 or Peer Web Services on Windows NT Workstation 4.0, you must install the Active Server Pages components after installing your server software. These components are not distributed with the Setup programs for Personal Web Server or Peer Web Services. To register and download the Setup program for these components, go to the Internet Information Server 3.0 page and click the Download link.
To use server-side scripting, create a file with an ASP extension, for example, filename.asp. The file may contain any combination of HTML, scripting (such as VBScript or JScript), and calls to components (ActiveX controls or Java applets written by yourself or bought off the shelf). ASP files on the server can be updated at any time. Simply save the changes to the file and the script will be automatically compiled the next time the Web page is loaded.
ASP includes five standard objects for global use:
<%@ LANGUAGE="VBSCRIPT" %> <!-- FILE: login.asp --> <HTML> <HEAD> <TITLE>Login Example</TITLE> </HEAD> <BODY> <% IF IsEmpty(Request.Form("Name")) THEN Response.Write "Please enter your Name" %> <FORM ACTION="login.asp" METHOD=POST> <INPUT NAME="Name" TYPE=TEXTBOX MAXLENGTH=20> <INPUT TYPE="SUBMIT" VALUE="Submit"> </FORM> <% ELSE 'User verification code goes here Response.Write "Welcome " & Request.Form("Name") & "!" END IF %> </BODY> </HTML>
One new technology (with a name that sounds amazingly like a type of candy) is scriptlet technology. Scriptlet technology enables Web authors create reusable objects using Dynamic HTML. The concept of scriptlets is simple: they are Web pages that contain script written according to specified conventions. To use a scriptlet, insert an <OBJECT> tag into another Web page and invoke the scriptlet by its standard URL. In Internet Explorer 4.0, the syntax for marking an object as a scriptlet is the MIME type text/x-scriptlet.
I've talked a lot about scripting in the context of a Web browser, but you can also use the Windows Scripting Host to use script outside of a browser. The Microsoft Scripting Host is a language-independent scripting host for ActiveX scripting engines on 32-bit Windows platforms. In the future, the Windows Scripting Host will be integrated into Windows 98, Windows NT Workstation version 5.0, and Windows NT Server version 5.0. Currently, the VBScript and JScript engines are provided with the Windows Scripting Host. It can be run either from the command line (cscript.exe) or through Windows (wscript.exe). The Windows Scripting Host is ideal for non-interactive scripts that perform administrative tasks. Full documentation for the Windows Scripting Host is available from the Microsoft Scripting site .
This article is designed to provide you with some background information about scripting in general and to give you pointers to more information. There's plenty of information on the Internet that covers scripting, including technical articles, documentation, Web sites, and samples. This list contains the promised pointers (in the form of links) to some of these resources. With these links in hand, you should be able to start your scripting today.