Copyright ©1996, Que Corporation. All rights reserved. No part of this book may be used or reproduced in any form or by any means, or stored in a database or retrieval system without prior written permission of the publisher except in the case of brief quotations embodied in critical articles and reviews. Making copies of any part of this book for any purpose other than your own personal use is a violation of United States copyright laws. For information, address Que Corporation, 201 West 103rd Street, Indianapolis, IN 46290 or at support@mcp.com.

Notice: This material is excerpted from Running A Perfect Web Site with Apache, ISBN: 0-7897-0745-4. The electronic version of this material has not been through the final proof reading stage that the book goes through before being published in printed form. Some errors may exist here that are corrected before the book is published. This material is provided "as is" without any warranty of any kind.

Chapter 14 - More Scripting Options

As the World Wide Web has expanded and included more and more information, users have clamored for more interactivity beyond "point-and-surf." Especially with the advent of online information requests and product ordering, the need has developed for efficient data gathering and validation without the time-consuming and cumbersome process of developing CGI scripts and the inherent slow transmission of information across phone lines.

Enter the new world of scripting, with JavaScript and Visual Basic Script. With a compatible browser or add-on software components, much of the necessary interactive work is accomplished on the client machine without the need for exchanging information back and forth with the server.

In this chapter, you will find:

  • What functionality scripts add to htmL documents
  • The basics of Netscape's JavaScript
  • What is possible with Microsoft's Visual Basic Script
  • New options for linking outside applications with ActiveX and Network Loadable Objects

Concepts

Scripts are small sections of code embedded in htmL tags or stand-alone sections of commands which are triggered by specific events in the document.

Normal htmL tags define static page appearances (headings and graphics), user interfaces (forms and links), and other features in addition to the text that appears on the screen. Scripts add interactivity to normal htmL tags by looking for events such as mouse clicks, mouse movements, and entering and leaving form fields.

For example, the tag <input type="button" value="Click Me, Please" onClick="sayHowdy()"> is the normal definition of a button up to the onClick statement. This addition to the tag calls a function called sayHowdy when the button is pushed.

Functions are defined using htmL script tags. If the browser does not recognize the script tag, the actual tag will be ignored unless and any subsequent text will be handled like any other text on the page.


Using script tags with htmL documents requires the following format:

<SCRIPT> 
Statements... 
</SCRIPT>


The optional, but recommended, attribute "language" specifies which scripting commands are being used:

<SCRIPT LANGUAGE="JavaScript">
JavaScript statements... 
</SCRIPT>


The language specification for Visual Basic Script is "VBS." the There is no limit to the number statements enclosed by script tags, or the number of occurrences of scripts in an htmL document.

JavaScript and Visual Basic Script, while similar in purpose and function, are implemented in different ways. JavaScript capability is included as part of the browser, notably Netscape 2.0. No additional files or programs are needed to add JavaScript capability, just an htmL document embedded with a valid script.

At the moment, Visual Basic Script is an add-on application which requires a set of VBS files on the client machine in order to function, and are included with Internet Explorer 3.0. When the browser finds the <script> command denoting VB Script, it will invoke the VB compiler add-on to handle the text denoted by the tags.

Since VB Script is a subset of Microsoft's Visual Basic programming language, it is likely that it will remain a separate application from the browser, although the two will be closely linked.

Both script languages discussed in this chapter allow Web authors and administrators to add interactivity to Web pages, including functions to respond to queries, ask questions, validate data, calculate expressions, and link to external controls and applications.


Checking for Helper Applications

How do I know if a user has the proper "helper application" or right browser to view my page? In two words, you don't. Unless you have control over the types of browsers end-users have on their computers, it's a good idea to identify pages that require compatibility with a script language.


To prevent your script from appearing on-screen with an incompatible browser, it's also a good idea to encompass the material between the <script> and </script> tags with comment htmL tags <!-- and -->. This will prevent your script from cluttering an otherwise attractive page.

When planning which scripting language to use, keep in mind that not all browsers support all scripts, if any. At publication, Microsoft announced support for JavaScript in its Internet Explorer, while Netscape has not yet reciprocated for VB Script. Other scripting possibilities are also on the horizon based on other popular Web languages, including Tcl, Python and Caml.

JavaScript

JavaScript is a set of commands that are included in htmL documents to add additional interactivity and functionality to Web pages. It began its life as LiveScript until collaboration with Sun Microsystems and its object-oriented language called Java caused a name change. Although JavaScript is not directly derived from Java, it is very similar in its form and construction. The primary difference between the two is that JavaScript is interpreted while Java is compiled.


Interpreted versus Compiled

Interpreted languages are evaluated line by line at run-time. Compiled languages are passed through a compiler, where it is converted into a form readily usable by the computer. While interpreted languages are easier to work with in areas like htmL page design, they sacrifice a lot in speed. A compiled program runs very fast since the interpretation of commands was done "ahead of time."

For example, a JavaScript function can verify that users enter valid information into a form requesting a ZIP code. Without any network transmission, an htmL page with embedded JavaScript interprets the text and alerts the user with a message for invalid input. Or, you can use JavaScript to perform an action (such as play an audio file, execute an applet, or communicate with a plug-in) in response to the user opening or exiting a page.

With an effective script, it is possible to respond without any network transmission to user-initiated events, such as mouse clicks and form entries.


JavaScript isn't Java

An important distinction to make is the difference between JavaScript and Java, which has caused confusion for a great number of folks. Java is a full-fledged object-oriented programming language. It makes use of a compiler to create stand-alone applications and browser applets. Applets are separate files downloaded to the client computer which can add special effects to htmL pages (scrolling banners are the current rage), but the code still resides in a separate file from the browser.

JavaScript, although related to Java, was developed by Netscape and does not require compiling. JavaScript exists as a set of commands supporting interactive levels above and beyond htmL without the need for server-based CGI programs.

JavaScript's vocabulary is much smaller than Java's, and is easily understandable by authors currently working with htmL. Java is a full-blown programming language, and benefits from knowledge of C and C++. Programming in Java requires a set of development tools, including a compiler and class library. All that is needed to take advantage of JavaScript is a text editor or htmL authoring application, and a compatible browser, such as Netscape Navigator 2.0.


For the most up-to-date information, check out Netscape's home page at http://home.netscape.com. It includes access to online documentation for JavaScript and links to pages exploiting JavaScript.

JavaScript Basics

In order to understand what is happening inside a section of JavaScript code and how to use it on your pages, it is necessary to understand a few key ideas of how JavaScript is constructed.

Objects and Properties

An object is similar to a noun. Cars, people, buildings, dogs, pencils, coffee cups can all be considered objects. They're tangible things we can touch and feel. Properties help define the object. They can be variables or other objects.

Let's create an object called libraryBook with the properties of title, author and dueDate. In JavaScript, we can define the object like this:

libraryBook = new checkOutBook("Return of the Native", 
    "Thomas Hardy", "04/15/96")

This line calls a function which results in a creation of new object with the following values:

libraryBook.title = "Return of the Native"
libraryBook.author = "Thomas Hardy"
libraryBook.dueDate = "04/15/96"

Writing a function to create an object is covered later in this section.


JavaScript is case sensitive, which can lead to confusion when creating objects and errors at runtime. For example, libraryBook and LibraryBook would be two different objects in JavaScript. It is important to strictly adhere to one style for naming items in JavaScript - your sanity depends on it.

Now, include another object called libraryInfo with the properties of branch, address, phone, which contains the following values:

libraryInfo.branch = "Downtown"
libraryInfo.address = "111 Higgins St."
libraryInfo.phone = 4065551212

To add more information to our libraryBook example, add the libraryInfo:

libraryBook.publicLibrary = libraryInfo

Here's what just happened. A new property named publicLibrary was added to libraryBook. This new property was assigned the value from the libraryInfo object. The properties for libraryBook are listed in table 14.1.

Table 14.1 Values of libraryBook Object

Object/property name Value
libraryBook.title "Thomas Hardy"
libraryBook.author "Return of the Native"
libraryBook.dueDate "04/15/96"
libraryBook.publicLibrary.branch "Downtown"
libraryBook.publicLibrary.address "111 Higgins St."
libraryBook.publicLibrary.phone 4065551212

JavaScript assigns values by adding properties to objects. If an object is added as a property, then the parent object (libraryBook) inherits the properties of the child (publicLibrary).

Methods and Functions

Methods and functions are the verbs of JavaScript. These are the items that "do" something. JavaScript includes a set of predefined methods and functions, in addition to allowing users to create their own special-purpose items.

Functions and methods begin with the function declaration:

function printTextAndLine (string) {
    document.write(string + "<HR>")
}

First, function lets the browser know that this is the definition of a process. Until the end of the function declaration is reached, no statements are executed. The function must be called somewhere else in the document before anything happens.

The name of the function follows. The name is used to invoke the function later on. The last item is an argument list surrounded by parentheses. In our example, there is only one argument called string.

The body of the function is enclosed in curly brackets, ({}). When the closing bracket is reached, the function definition is completed.


JavaScript text is treated like any other htmL text. Extra spaces and carriage returns are ignored, but should be used to make the code more readable. Normally in coding, a carriage return is used to delineate the start of a new command or line. In JavaScript, command lines are separated with a semicolon.

When a function is added to an object, it is called a method.

Continuing with the libraryBook example, let's define a new function called printCheckout:

function printCheckout() {
    document.write("Your book: " + this.title + "<BR>");
    document.write("  Due on: " + this.dueDate + "<P>");
}

This function is added to the object the same as another object:

libraryBook.printInfo = printCheckout 

To invoke the method requires a single statement:

libraryBook.printInfo().


There are two ways of formatting text inside JavaScript. The first uses standard htmL tags generated by the document.write function. In order for these to work, they must be sent to the screen encapsulated in quotation marks like any other text.

The second is with JavaScript codes, which are included in the string expression NOT enclosed in quotation marks. JavaScript formatting commands are listed in Table 14.2.

The following two statements would yield the same results, a break at the end of the line:

document.write("Something<BR>another line")
document.write("Something  \n another line")
Table 14.2 JavaScript Text Formatting Codes

Code Purpose
\b backspace
\f form feed
\n new line
\r carriage return
\t tab character

JavaScript can use an additional set of codes to format text displayed with document.write. These codes are included in the string with a "+" and no quotation marks.

Creating Objects

Creating objects is a two-step process.

  1. Create a function which defines the object.
  2. Assign a variable to the function using "new".

Going back once again to the libraryBook, a function to create a book object could look something like this:

function book(title, author, dueDate) {
    this.title = title;
    this.author = author;
    this.dueDate = dueDate;
}

Our library book is defined with the following statement:

libraryBook = new book("Return of the Native",
    "Thomas Hardy","04/15/96")


JavaScript supports a special object called this. In general, this refers to the calling object. It is especially useful for validating form information.

For example, the tag <input type="text" name= "ssn" width="9" onChange="validId(this)> will call the function validId with the information entered by the user in the ssn text box.

In turn, we can create other objects using the same definition:

libraryBook2 = new book("Life Among the Savages",
    "Shirley Jackson","03/18/96")
collegeLibraryBook = new book("Red Shirt, Green Shirt",
    "Sandra Boynton","05/01/96")

Variables

Unlike Java, JavaScript does not enforce explicit data types.


An explicit data type can only handle a specific type of data, such as integer, floating point decimal, string, or boolean. Implicit data types are defined on-the-fly as a value is assigned to the variable. For example, a variable called weekDay is assigned a number representing the day of the week, 3 for Wednesday. When it's time to print the text, the variable can change type by a simple expression such as, if weekDay = 3 : weekDay = "Wednesday".

JavaScript supports four basic kinds of variables: object, numeric, string, and date. As discussed earlier, JavaScript is based on objects. While similar to other variables, it is different in a key behavior. The "value" of objects are changed by adding properties, methods and other objects. So, while a variable can be a property of an object, an object is never a property of a variable.

The next two variables, numeric and string, are straight forward. Numeric is any number, integer or floating-point decimal. A string is any collection of characters, included letters, numbers and special characters.


JavaScript has a feature called automatic type conversion. This feature will convert a string variable to numeric and vice versa, depending on its use.

For example, the variable x is assigned to 10, and the variable increment is assigned to 3. The statement x = x + increment evaluates to 13. The first type encountered by JavaScript is numeric, so the second variable is also converted to a numeric value. If increment was assigned to Bob, the statement would return an error, since numeric conversion is impossible for Bob.

Using implicit typing, JavaScript has eliminated the need for commands found in other languages, such as val and str, used to convert strings to numeric values and vice versa. It also places more responsibility on the person writing the code to manage variables to ensure that inconsistent data types are not brought together in a 3 + Bob situation.

Dates

The date data type does not contain a "date" the way we normally think of a date. JavaScript calculates the date and time based on the number of milliseconds since midnight on January 1, 1970. It sounds a little complicated, but it is a fairly standard form of calculating dates and times with computers.

Where it starts to get complicated is assigning a new date variable. The date is entered yy,mm-1,dd,hh,mm,ss. Translated, this means entering the year, the month minus one, the day, hours, minutes and seconds. For example:

docFirstDay = new Date(96,0,13,6,15,00)

This creates a variable called docFirstDay with a value of January 11, 1996 at 6:15 am.

Accessing the current date requires creating a new variable, usually called today, the same way the docFirstDay was created. Then, each component is accessed through separate methods:

today.getMonth()
today.getDate()
today.getYear()
today.getHours()
today.getMinutes()
today.getSeconds()


Don't forget to add 1 to the month. JavaScript begins its year with January equal to 0.

You can add and subtract the values from date methods. For example, using the onLoad event handler, you could check the current date against the date the document was modified and inform the user if the information they're going to read might be out of date.


The date on the client's computer is used for all date calculations. So, if your date is based on the correct date and time, and the client computer is set to 1/1/85, any calculation based on the current time will be inaccurate.

Adding JavaScript to htmL

As seen in some of the previous examples, adding JavaScript to htmL is a fairly simple matter. There are a couple of points to keep in mind when deciding where to place the scripts.

  • When an htmL document is called by a browser, the page is loaded into memory before it's tags are evaluated and displayed. For this reason, it's best to place all function definitions inside the <head> tags at the beginning of the document, where they are loaded into memory before the user has a chance to initiate any events. The exception is JavaScript code which is executed with the rest of the page. It should be included inside the <body> tags so it is processed at the proper time.
  • Browsers incompatible with script languages will display any text inside the <script> tags as text, so it's best to use comment tags to hide it. Hiding the script will not interfere with a compatible browser's ability to load and run it.

With this ability in mind, JavaScript can reside in two places inside an htmL document.

  • As statements and functions using <script> tags.
  • As event handlers using htmL tags.

Scripts

Now that some of the basic building blocks are in place for creating JavaScript procedures, its time to try some examples.

The following script illustrates a simple script to display text on a page.

Listing 14.1 A Simple htmL Document with JavaScript

<html>
<head>
This is an htmL page.
</head>
<body> 
This begins the body of an htmL page.
<script language="JavaScript"> 
<!-- Hide text from old browsers
document.write("<hr>Hello from JavaScript.<hr>") 
alert("You have entered a JavaScript-powered page")
//finish hiding script -->
</script> 
That's all, folks. 
</body> 
</html>

Examining the code line by line reveals what is happening. First, under htmL commands, a simple text line is displayed on the screen. Then, the script flag is encountered, letting the browser know that the following lines will need to be interpreted as JavaScript commands.

The two JavaScript lines, alert and document.write, are both methods for displaying information on the screen. The alert function beeps and displays a dialog box with a message, which can then be cleared by the user. The next line displays text on the screen like normal htmL text. Since JavaScript commands are interpreted separate from the browser, any formatting needs to be inserted into the string before it is sent to the page. In this example, the <hr> tag inserts a horizontal line above and below the JavaScript text to separate it from the htmL text on the screen.

Fig. 14.1 - The display generated by Netscape Navigator 2.0 using the script in listing 14.1.

Fig. 14.2 - The display generated by a noncompatible browser only shows htmL text. The script commands are ignored and hidden by comment tags.

The next example illustrates the placement of functions and events that trigger them.

Listing 14.2 A Simple JavaScript Event-Handling Function.

<html>
<head>
This is an htmL page.
<script language="JavaScript">
<!-- Hide text from old browsers
function outTheWindow() {
newWin = open("","DisplayWindow",
    "toolbar=no,directories=no,menubar=no");
newWin.document.write(
    "<HEAD><TITLE>htmL On The Fly!</TITLE></HEAD>");
newWin.document.write(
    "<H1>Now is the time to make htmL work.</H1>");
}
//finish hiding script -->
</script>
</head>
<body> 
This begins the body of your average htmL page.
<form>
<input type="button" name="button" 
    value="Press Here For Results" 
    onClick="outTheWindow()">
</form>
</body> 
</html>

When the document is loaded, the outTheWindow function is defined for future use. A button is drawn on the screen inside a form. Clicking the button is detected by the onClick event handler (see following), which triggers the function.

The function itself is the basis for some intriguing possibilities with script languages. JavaScript opens a new window in the browser, and begins to generate htmL code. The initial value which is left blank can also contain a URL to another file on your server, or any other address on the Web.

Event Handlers

Event handlers, coupled with the basic programming functions, allow Web developers to implement client-based interactivity. JavaScript includes a basic set of event handlers which provide the capability to deal with most things a user will do with a form or the mouse pointer.

Table 14.3 JavaScript Event Handlers

Name User event Example
click Click on form element or link onClick
mouseover Mouse pointer moved over a link or anchor onMouseOver
blur Remove input focus from form element onBlur
focus Form element selected for input onFocus
select Form element's input field selected onSelect
change Changed value of text, textarea, or select element onChange
load Navigator loads page onLoad
unload User exits the page onUnload
submit Form is submitted onSubmit

The following script shows how additional information can be provided for links to other items by using the onMouseOver event to place a custom message in the status bar.

<html>
<body>
If you need more information about JavaScript, check out
<a href="http://home.netscape.com/" 
    onMouseOver="window.status='The Netscape Home Page'; 
    return true"> Netscape.</a>
</body>
</html>

Fig 14.3 - The display generated by listing 14.2. Note the status bar at the bottom of the screen, where the link's URL is replaced by text from the event handler tag.

The real power of event handlers is evident in validating user information. Look at the following script.

Listing 14.3 A Script To Validate User-Entered Information

<html>
<head>
<script language="JavaScript">
<!-- Hide script from old browsers
function checkPassword(string) {
if (string="password") {
newWin = open("download/safezone/index.html","DisplayWindow", 
    "toolbar=no,directories=no,menubar=no");
}
else {alert("Invalid password.")
} 
// end script hiding -->
</script>
<body>
Please type your name in the box:
<form>
<input type="password" name="name" size=8 
    onBlur="checkPassword(this.value)" value="">
</form>
</body>
</html>

After entering a password in the form box, it is checked against the generic password. If "password" is entered, then a new window is opened with a different htmL document.

Obviously, this is not a secure way to deal with passwords, but you get the idea of the kind of validation and entry-checking possible without accessing the server.

The Future of JavaScript

As of publication, JavaScript is implemented as part of Netscape 2.0 and 2.01. This is not the end of its development, however, as Netscape has reserved words for future properties and methods. Proposed htmL specifications will limit script actions to events generated within form tags, but currently, JavaScript capabilities extend beyond the defined limits. Two examples are the OnLoad and OnUnLoad events, triggered when a page is entered and exited, which are possible to include within body tags.

Netscape also has plans to support JavaScript from the server through a compiled form of the language. When a Web page containing server-side JavaScript is encountered, it will only perform the code locally. This type of application can be used to track the current browser connection and other information from the user. In this form, JavaScript could be pressed into CGI service without dealing with Perl or C. Future plans call for JavaScript related applications to provide access to standard database products.

JavaScript can also interact with the exposed properties and methods of Java applets and plug-ins. Once the object is declared on the page, JavaScript can get and set properties and call methods within scripts by using its standard object hierarchy, beginning with the class or plug-in name as the object name.

Visual Basic Script

Visual Basic Script, also known as VB Script, is a new scripting language packaged with Microsoft's Internet Explorer 3.0. VB Scripts are connected to events, defined by attaching "On" handlers to htmL tags. The event triggers the script, which interacts with its environment through a set of objects representing htmL page element, history list, plug-in applications, object files and applets.

The syntax of VB Script is based on Visual Basic, although VB Script offers a much smaller and simpler set of commands to work with. It is used to validate form data, create new Web pages on-the-fly, and perform other operations with user input.

While VB Script resembles the object-oriented JavaScript, it is not necessary to understand object-oriented programming.


Visual Basic Script Isn't Visual Basic

VB Script is described by Microsoft as a "fast, lightweight" subset of Visual Basic designed for use inside htmL pages. While requiring a compiler on the host machine, VB Script has no ability to create user interfaces. Every item manipulated by VB Script must first exist in the htmL page. The files required to integrate VB Script with a browser take approximately 200K of disk space.

Microsoft Visual Basic is a programming language geared towards developing applications for Windows. It includes editors, debuggers and compilers for the creation of independent applications. It consumes approximately 1 MB of disk space for the basic set of tools.


Updates on Microsoft's development and support of Visual Basic Script can be found through Microsoft's Web site at http://www.microsoft.com/intdev/vbs/.

Visual Basic Tools

Since VB Script is a subset of Visual Basic, it is upwardly compatible to Visual Basic for Applications which is upwardly compatible with Visual Basic. For Web managers and developers already familiar with Visual Basic, the trip to productivity and interactivity will be a short one.


Browsers often employ "helper applications" to extend the capabilities of htmL documents. Some of these applications are built in or generally included as part of the software package (some sound and graphics), while others are added later by the user (animation and compressed files).

If a browser sees an item tag it doesn't recognize, it checks its list of helper applications and calls the matching program to handle the information between the tags.

Data and Variable Types

VB Script's only data type is called a "variant." A variant can contain different types of information depending on how it's assigned or used. Since it's the only data type in VB Script, all functions return it.

Since different types of information may be passed to the variant, the command VarType is used to return information about what kind of data is stored within. At a simple level, variants contain string or numeric data. If it is used in a mathematical equation it is treated as a number; if used in a string it behaves like a string.

Since the basic types of data come in many varieties, the variant is equipped with subtypes to help further define its use. Subtypes include boolean, integer, single and double (floating point numbers), date and string. Information can be translated from one subtype to another using the conversion functions included with VB Scsript.

Variables are declared using the Dim statement. For example:

Dim TotalBill

creates a variable called "TotalBill", which is a variant. Its subtype is empty, since no value has been assigned yet. Variables can also be declared implicitly by using a valid name somewhere within your script. For example:

ItemCharge = 10.50

creates a variable named "ItemCharge", which is a variant of subtype single, since it has been assigned a floating point value.


Standard Naming Rules

Variable names follow a simple set of standard rules which also apply to all other user-defined items.

Names must begin with an alphabetic character.

It can't contain an embedded period.

Length is restricted to 255 characters.

Must be a unique name within the scope it's used.

When a variable is declared within a procedure, only commands and statements within that procedure can access or change the value of the variable. This is called local scope. If a variable needs to have a scope that extends to all procedures within a script, it should be declared outside of a procedure definition. It has script-level scope.

Local scope variables retain their value only while the procedure is running. Once the procedure returns control to the script, the variable is lost until created again by calling the procedure again. A script-level variable will maintain its value until the script is completed.

VB Script also supports arrays. The only difference in declaration is the addition of parentheses with a the number of elements.

Dim ExecutiveBoard(12)

Since all arrays include a 0 element, the above example contains 13 elements. Arrays can contain up to 60 dimensions.


To create a dynamic array, whose size can change during run-time, use the ReDim statement.

ReDim ItemsOrdered()

Note the difference with the parentheses. A dynamic array does not use a size value.

To increase or decrease the size of the array, use ReDim with a value. Changing the number of elements will clear existing values in the array unless the Preserve statement is used.

ReDim ItemsOrdered(6)
...
ReDim Preserve ItemsOrdered(7)


Procedures

Procedures come in two varieties with VB Script, Sub and Function.

A Sub procedure can accept parameters and perform actions, but does not return a value when it is completed. If it doesn't accept parameters, then it is declared with a set of empty parentheses.

Sub AddNumbers(First,Second)
      NumSum = First + Second
      MsgBox "The sum of " & First & " and " & 
        " Second " is " & NumSum & "."
End Sub

A Function is similar to a Sub, but it can return a value. This is accomplished by assigning a value to the function name.

Function AddNumbers(First,Second)
      AddNumbers = First + Second
End Function


Like functions in JavaScript, Subs and Functions should be declared in the <head> portion of an htmL page. This ensures the procedures are loaded and ready by the time the user sees the page and has a chance to act.

Working with Forms

One of VB Script's most powerful uses is for data validation without server interaction. This makes it possible to ensure users submit information that your server is expecting, preventing unexpected error messages.

Values from forms are referenced using their names. For example, a text box named "SSN" is accessed using SSN.value in a calling function.

Using Objects

In order for VB Script to get and set object properties from OLE controls or Java classes, it is first necessary to define the object using the <object> declaration with the "ID" parameter to identify it.

Once it is inserted, it's properties and methods are invoked by using the appropriate syntax.

For properties and values, use the name and a dot:

PictureButton.Caption = "Display Image"

For event handlers, use an underscore:

Sub PictureButton_Click ()
...
End Sub

Embedded Objects

One key item that is included with Microsoft's entry into scripting is control of Object Linking and Embedding (OLE) controls, expanded and renamed as ActiveX.


Getting ActiveX

An ActiveX software development kit (sdk) is available for download from Microsoft's Internet Developer Web site at http://www.microsoft.com/intdev/sdk/sdkdownl.htm. It includes ActiveX development tools and a copy of Internet Explorer 3.0. This is a very large download (12MB), which is also available in 2MB or 1MB chunks if your modem is slower or your Internet connection is less-than-reliable.

OLE controls, also called OCXs, are graphical objects with well-defined external interfaces which may be manipulated by Visual Basic and other Microsoft-related tools.

These controls are embedded in htmL documents in formats similar to Netscape's plug-ins, although the formal standard is still under development.

ActiveX expands the capabilities of OCX controls by adding additional tools for embedding a wide variety of software components directly into a Web page, including graphics viewers, animation sequences, credit card transaction objects or spread sheet applets. For example, the ActiveMovie API released by Microsoft is an ActiveX control which plays video sequences within the browser.

ActiveX controls can be included as part of VB Script or JavaScript applications to extend interactivity and functionality of Web pages. It will also extend beyond Microsoft's browser to Netscape with a plug-in module co-developed by Microsoft and nCompass Labs. By implementing multiple-browser support, ActiveX could become a very popular way of including live objects in htmL documents.

The new object controls also allow authors and developers easier access to client-server communications, including WinSock TCP, FTP Client, HTTP, htmL, POP, SMTP and NNTP, in addition to


For the most recent W3 Consortium proposal regarding htmL embedded objects, check out the W3 Web site at http://www.w3.org/pub/WWW/TR/WD-insert9512221.html. This site also includes other htmL and Web standards information useful for Web administrators and authors.

Two important properties planned for Internet-aware OCXs are known as "ReadyState" and "OnReadyStateChange." This will allow specific OCXs to declare their current state and trigger actions based on changes to that state. This could lead to interesting developments in OCX planning, as it allows an OCX to progressively load itself while supporting greater levels of functionality and responsibility for actions.

For example, a button could be active as soon as the button state code is loaded, even though graphics display is not fully rendered or active.

But, Microsoft is not alone in its pursuit of easy-to-use embedded objects. Oracle has developed Network Loadable Objects, called NLOs for its PowerBrowser software. NLOS are programs and program modules which loaded and run on the client machine, and are similar in function to a CGI application on the server. NLOs offer the developer access to the user interface and client network access facilities, which are especially useful for long-term operations which must maintain states across network access.

One of the first ready-made NLO programs being offered by Oracle supports integrating a Netscape plug-in interface, so htmL pages with this type of content can be loaded and displayed correctly by PowerBrowser.

NLOs are similar to Visual Basic controls in the sense they are third-party applications which can be plugged into the browser to implement new functions. However, this also means they share a common drawback. NLO programs are binary objects, which makes it easier to insert viruses or Trojan horses into the code. One recommendation is to distribute NLOs in combination with their source code so they can be inspected and compiled by the user. However, since NLOs are similar to other plug-in modules, they can also be downloaded and scanned for corruption before running it on your system.

CScript

CScript is an extension of the Server Sides Includes specification. It is implemented as a part of SSI+. CScript is an enhanced subset of the C programming language. With CScript you are able to include complete C like programs within an htmL page without needing to compile the program. CScript is the natural complement to JavaScript; while JavaScript is client based, CScript is server based. Like JavaScript, CScript follows the C syntax conventions. Anyone familiar with C will be able to use CScript. CScript is native to WebQuestNT 2.0, and currently is only available with WebQuestNT 2.0.


More information about CScript is provided with WebQuestNT 2.0 files, including SSIPLUS.htm. Also information is available at Questar's Web site, http://www.questar.com/.

Features

CScript is a complete programming language. Most of the features of C are available within CScript. Like C, CScript includes variables, flow control, operators, string manipulation, type casting, assignment and outputting. Also CScript has some unique features relevant to the World Wide Web like ODBC, Cookies, and SMTP mail. The following is a quick overview of some of the elements of CScript.

CScript Basics

The CScript tag allows you to embed C like code directly into a htmL file. All the semantics and features of a high level object-oriented language like C are available without a compiler or the limitations of CGI. CScript is added to a htmL file using the opening <!--#cscript tag and the closing --> tag.

The following example shows a simple CScript that calls a .dll called WQODBC.dll. This .dll connects to the "nwind" datasource, queries the datasource and returns data in the specified format.

Listing 14.4 ODBC Manipulation Using CScript

<!--#cscript
WQODBC,Connect("nwind",NULL,NULL,FALSE,LOCAL_SOCKET);
WQODBC,Query("nwind","SELECT Freight,Freight,Freight,Freight 
    FROM Orders","String: %s<BR>Currency(10.2f): $%10.2f<BR>
    Currency Left Aligned(-10.2f): $%-10.2f<BR>
Percent: %%%.2f<P>",TRUE,LOCAL_SOCKET);
WQODBC,Disconnect("nwind",FALSE,LOCAL_SOCKET);
-->

In the next example, flow control and logical operators are used to find out if the variable USER_NAME matches the name on a hard coded list. If the name matches then the second message is displayed. If the name does not match the first message, "You are not on the list" is displayed.

Listing 14.5 Flow Control and Comparison Using CScript

<!--#CScript
if( !strstr( "Kevin Alan Sue", USER_NAME )
{
print( "<p>You are not on the list" );
exit(0);
}
else
print( "<p>Yes,  you are on the list" );
-->

Variables

All variables are represented as self-allocating objects, and are available in the following formats:

  • Form objects, like standard SSI environment variables
  • Ordinals, standard C data types: int, float and char.
  • Nonstandard data types: text, logic and dword
  • Strings, text objects
  • Structures, user defined data types
  • Arrays, sequential list of CScript data types and structures.

Flow Control

A complete implementation of flow control is available with CScript using standard operands.

  • if, else, switch
  • for, while, goto
  • break, exit

Operators

Mathematical, logical and comparison operators are implemented as in C.

  • Math: +, -, *, /, ^
  • Logic: &, |, !
  • Comparison: ==, >, <, >=, <=, !=, !>, !<


QUE Home Page

For technical support For our books And software contact support@mcp.com

Copyright © 1996, Que Corporation


Table of Contents

13 - CGI Scripts and Server APIs

15 - Search Engines and Annotation Systems