Form-Data Handling in Server-Side JavaScript
By Robert W. Husted
Send comments and questions about this article to View Source.
Click here for printer-friendly version
In the View Source article CGI vs. Server-Side JavaScript for Database
Applications, Z. Peter Lazar and Peter Holfelder detailed the advantages of using
server-side JavaScript (SSJS) instead of the Common
Gateway Interface (CGI) to develop Internet/intranet/extranet applications. Here we'll explore SSJS applications vs. CGI
applications a bit further and use the SendMail
object, a new feature in Enterprise Server 3.0, to demonstrate the capabilities of cross-platform SSJS applications.
You'll find JavaScript to be an excellent language for developing all types of applications; anything
that you traditionally develop with Perl or other CGI scripting languages can be developed in SSJS. The advantage of using SSJS
is that you can use one language syntax for all your Web projects (Java and JavaScript). In addition, SSJS comes bundled with Enterprise Server 3.0, so once your
server is installed and configured, you're ready to start writing JavaScript applications immediately.
One application that seems to appear on every Web site is the form-data handler CGI. This CGI collects data from a form
submission, packs it into an e-mail message, and ships it to someone in the company or organization.
CGIs are used instead of simple mailto commands to ensure that required fields have been entered and to provide some
sort of feedback to the user, indicating that the submitted data has been received. The
example SSJS application discussed in this article can replace a large number of these existing CGIs on your Web site, giving
you the following benefits:
- Central control of data submitted via forms on your Web site. You would need to change the code in only one place
to make a change to the way all forms are handled on your site.
- Easy creation of additional e-mail-enabled forms. Since the functionality of the application is controlled by the
calling form, no additional programming is required. Anyone on the site could create an e-mail-enabled form that
instantly conforms to company standards. This gives the IS department greater control over the way form data is collected,
routed, and stored on the site.
- Ability to send HTML-formatted e-mail. The new SendMail object makes it easy to send HTML-formatted e-mail,
so you can mail the form data in a rich text format.
- Fewer CGIs on your site. Nobody likes an unruly Web site; you can eliminate up to 80% of the CGIs on your site by using this one application.
- Easy-to-maintain code. Perl, due to its extreme flexibility in syntax, is generally difficult to read and maintain, while JavaScript's syntax is similar to the popular C/C++ and Java languages, all of which are easily maintained.
INTRODUCING THE SENDMAIL
OBJECT
I used the new SendMail object in Enterprise Server 3.0 to create the example application described in this article. For
those of you interested in getting started immediately with this new object, here is the syntax
for sending a basic e-mail message:
var msg = new SendMail(); // CREATE SENDMAIL OBJECT
msg.To = "john@doughboy.com"; // RECIPIENT OF MESSAGE
msg.From = "bill@company.com"; // SENDER OF MESSAGE
msg.Subject = "Hawaii Sweepstakes"; // SUBJECT OF MESSAGE
msg.Body = "Hey John, you WON!"; // BODY OF MESSAGE
msg.send; // SEND THE E-MAIL MESSAGE
The SendMail object will be explained in more detail below. For
now we'll focus on what you can do with this new object. You can use it
to easily send e-mail directly from your SSJS application. For example,
you could do any of the following:
- Send form data via e-mail (the example application accomplishes this task).
- Send notifications to managers about all open Purchase Orders in a database.
- Send out a weekly departmental newsletter in HTML format.
- Send a quarterly feedback form to all company employees -- and a daily "tickler" to all employees who have not yet filled out the form.
- Automatically send an e-mail message on Friday morning to everyone in your group reminding them to update their weekly status reports.
- Send an e-mail message to the department manager every morning with a list of open vacation requests.
The possibilities are virtually endless. Read on to learn how to use the SendMail object to solve form-data collection
issues and to send HTML-formatted e-mail.
CONTROLLING FORM DATA
THROUGH HIDDEN FIELDS
You've probably created at least one CGI that handles data submitted via HTML forms. However, since most of these CGIs tend to
be very similar in functionality, it makes sense to create a single application that handles
form data. The application should be coded in such a way that the form creator can control the CGI's functionality by using
hidden fields in the form.
Let's say we want to control who the e-mail is sent to and what the subject is from our calling form but don't want our users
to see that information. By using hidden fields in our HTML form, we can secretly send the data
we need without confusing the user with additional entry fields. In the form we would have the following code:
<FORM ACTION="/old?u=http%3A%2F%2Fmachine.domain.com%2Fforms&y=1999"...>
...
<INPUT TYPE=HIDDEN NAME=TO VALUE="bob">
<INPUT TYPE=HIDDEN NAME=SUBJECT VALUE="Hawaii Sweepstakes Offer">
...
</FORM>
Fields of type HIDDEN are not displayed when the HTML page is rendered in the browser window. Users will never see these fields,
yet they will be submitted with the rest of the fields. In our server-side application
we would have the following code to get the two HIDDEN values shown above:
var sendTo = request.TO;
var subject = request.SUBJECT;
Note: Field names are case-sensitive.
Now that we have the values, we can send the form data to the specified
person (bob) with the subject "Hawaii Sweepstakes Offer." If we produce
another promotion, say for a new Porsche, and we want the e-mail to go
to Susan, we don't need to create a new JavaScript application; we just have to create a new form with the following fields in it:
<INPUT TYPE=HIDDEN NAME=TO VALUE="susan">
<INPUT TYPE=HIDDEN NAME=SUBJECT VALUE="Porsche Promotional Offer">
Once we've created the SSJS application, we can easily e-mail-enable any
form on our Web site and control where the data is sent and what the subject
is, without having to alter our JavaScript program. Extending this idea,
we can create a full-featured application that will handle nearly any form
on our Web site. That's the purpose of the example application.
THE EXAMPLE APPLICATION
The example application (UNIX/NT),
originally a Perl CGI that took over a week to code and refine, was coded
in SSJS in less than a day. One advantage that I noted immediately was
my ability to reuse the skills I'd learned from using client-side JavaScript
(CSJS) to code the server-side application, since the language is the same
(JavaScript). Traditionally, developers have written their client-side functions in JavaScript and their server-side programs in Perl, C/C++, and so on. Switching back and forth between two different language syntaxes
can get confusing; just commenting the code can get you into trouble (comments
in JavaScript start with "//" whereas comments in Perl start with "#" --
you cannot mix the two without introducing serious errors into your code).
Using one syntax greatly improves your programming efficiency, reduces the likelihood of errors, and allows for greater code reuse.
The example application lets you do the following:
- Send formatted e-mail messages containing form data to a recipient (or mail alias) at a given company. For example,
let's say Bob has a Hawaii Sweepstakes Promotion with a form on the Web site. The example application
will enable you to send Bob the data from the form so that he can randomly select a winner. All you have to do is add some
hidden fields to Bob's form; you don't have to program a new CGI to handle Bob's form data.
- Check to ensure that required fields have been filled out. Certainly you would not want a form to be submitted if the
name, phone number, and reply e-mail address fields were blank or if all fields were blank.
- Display a short HTML-formatted response to the user. After submitting a form, users like to see a confirmation that
their data has been received -- something like "Thank you for your interest in our Hawaii Sweepstakes;
your data has been forwarded and you will be hearing back from us soon."
- Send an automated e-mail confirmation message to the user. Sometimes it's nice to send the user an e-mail confirmation
that the form data has been received. This confirmation can be used either in addition to or instead
of the HTML-formatted response just mentioned.
- Write pipe-delimited data to a specified log file (provided the subdirectory already exists). Pipe-delimited data
looks like |John|Doe|415.555.1212|john@doughboy.com|, and it's very easy to import such delimited data directly into a database.
- Redirect the user to another page (rather than returning a short HTML-formatted response). This makes it possible for
you to display a customized HTML-formatted response to the user.
Note: If you plan to use the example application on your Internet site, please disable portions of the automated email
confirmation message and HTML-formatted response functionality as directed by comments in the code.
Now we'll look more closely at what the example application does. (An explanation of how to implement and use the application
is included in the application's help document, so we won't discuss that in this article.)
Checking for Required Fields
The first step in handling the form data is to check for required fields. To do this, simply parse the comma-delimited list
of required field names specified in the calling form. (This is somewhat lengthy and therefore
won't be shown in this article; you can find it in the application source code [UNIX/NT]). If no required fields are missing, loop through all the fields, adding the name/value pairs to the outgoing e-mail message or log file entry.
The following code allows you to loop through all form values that were
submitted with the POST method (the preferred method for submitting form
data):
for (var propName in request) {
// EXCLUDE DEFAULT REQUEST OBJECT PROPERTIES FROM MESSAGE
if (propName == 'ip' ||
propName == 'protocol' ||
propName == 'method' ||
propName == 'agent' ||
propName == 'auth_user' ||
propName == 'auth_type' ||
propName == 'uri') {
}
// EXCLUDE FORM-HANDLING NAME/VALUE PAIRS (HIDDEN FIELDS) FROM MESSAGE
else if (propName == 'TO' ||
propName == 'SUBJECT' ||
propName == 'TITLE' ||
propName == 'REQUIRED' ||
propName == 'LOG_DIR' ||
propName == 'LOG_FILE' ||
propName == 'REDIRECT' ||
propName == 'HTML_FORMAT' ||
propName.indexOf('e-mail_REPLY') != -1 ||
propName.indexOf('e-mail_REPLIER') != -1 ||
propName.indexOf('HTML_RESPONSE') != -1) {
}
else {
...
// ADD THE NAME (propName) AND VALUE (request[propName]) TO THE MESSAGE
message += "\n" + unescape(propName) + " = " + unescape(request[propName]);
...
}
}
Sending HTML E-Mail Using the SendMail Object
You can send plain text or rich text e-mail directly from your JavaScript application using the new SendMail object.
Once all the name/value pairs from the form have been packed into a variable, you're ready to send
an e-mail message containing the form data to the user specified in the calling form. (Only the user name is specified; the
domain name is hard-coded in the application to prevent other companies from using your scripts to
process their form submissions.) The message variable can contain
HTML tags if you're sending HTML e-mail, so you can either read the contents
of an HTML file into the variable or construct your HTML-formatted message
on the fly.
Plain text message:
var message = "Congratulations Bob, you've won a trip to Hawaii!";
Rich text message:
var message = "<P><FONT SIZE=+3>Congratulations Bob!</FONT>\n" +
"<P>You've won a trip to Hawaii!";
var to = "bob@company.com";
var from = "hawaii@company.com";
var subject = "Hawaii Promotion";
To send plain text or rich text e-mail directly from your JavaScript application,
first create a SendMail object:
var msg = new SendMail(); // CREATE SENDMAIL OBJECT
Next specify the e-mail address to which the e-mail will be sent (To),
the reply address (From), the subject of your message (Subject),
and the content or body of the message (Body):
msg.To = to; // RECIPIENT OF MESSAGE
msg.From = from; // SENDER OF MESSAGE
msg.Subject = subject; // SUBJECT OF MESSAGE
msg.Body = message; // BODY OF MESSAGE
If you want to send rich text e-mail, use the following code to tell the
SendMail object to send an HTML-formatted e-mail message:
// USE THE VALUES BELOW FOR SENDING HTML E-MAIL (PLAIN TEXT IS THE DEFAULT)
if (request.HTML_FORMAT) {
msg["Content-Type"] = "text/html;";
}
By specifying that the Content-Type is "text/html;",
you instruct the SendMail object to send an HTML-formatted message
rather than a plain text message. If your HTML document has relative links
(/announcements/announce_24Jan97.html) for graphics and URLs instead
of fully qualified links (http://machine.domain.com/announcements/announce_24Jan97.html),
you can use the following code to tell the mail client where the relative
links begin:
// TELLS CLIENT WHERE RELATIVE LINKS BEGIN.
// (BASETAG EQUIVALENT -- USED IF LINKS IN THE HTML DOCUMENT ARE NOT ABSOLUTE)
msg["Content-Base"] = "http://machine.domain.com/";
Now you can send the e-mail message:
// SEND MESSAGE
if (!msg.send()) {
// MESSAGE NOT SENT, DISPLAY ERROR MESSAGE
write("SendMail Error: <b>" + msg.errorCode() + "</b> " + msg.errorMessage() + "\n");
}
Installing the Application on Your Server
If you want to install and test the example application, you need to
do the following:
- Enable server-side JavaScript using Netscape Enterprise Server Administration (select Server/Programs/Server Side JavaScript).
- Specify your mail server using Netscape Enterprise Server Administration (select Server/Server Preferences/Network Settings/MTA Host:).
- Build the SSJS application (run the build file).
- Add the application in Netscape Application Manager (http://host/appmgr).
When you test the application (http://host/forms), the help file will be displayed by default to tell you more about
the application, including how to control it from the calling form. The help file includes a sample
form to help you test the application. Please refer to this sample any time you have questions about setting up your own forms.
THE SSJS ADVANTAGE
You'll find that server-side JavaScript is easier and faster for development
of Web applications than traditional CGI approaches. You'll also realize
benefits as you use a common language syntax (Java/JavaScript) in all your
development efforts. Please contact View Source if you're interested
in other articles related to the use of server-side JavaScript and related technologies.
View Source wants your feedback!
Write to us and let us know
what you think of this article.
The author wishes to express appreciation to Paul Dreyfus for his insight and skillful guidance during the preparation of
this article, and to Basil Hashem, whose encouragement and assistance made this article possible.
Robert
W. Husted was formerly a Web Production Engineer and Technology Evangelist at Netscape Communications. He wrote
the Suggestion
Box application for Netscape
AppFoundry Online and assisted in the development of Netscape
Insight. Robert likes long walks on the beach, racquetball, wind surfing,
and playing with his two
children, whose recent ketchup assault on the living room couch caused him much angst.
(9.97)
- Related Readings:
-
Any sample code included above is provided for your use on an "AS IS" basis, under the Netscape License Agreement - Terms of Use