At the Forge - Prototype

Prototype eases the burden of using JavaScript in Ajax.
Ajax

One of the most common reasons for the recent interest in JavaScript is the growing interest in Web applications that incorporate Ajax techniques. As we have seen in the last few installments of this column, Ajax is nothing more than 1) creating an XmlHttpRequest object, 2) writing a function that sends the HTTP request with that object, 3) setting the event handler to invoke that function, and 4) writing a function that is invoked when the HTTP response returns. It isn't particularly difficult to deal with all of these things in code, but why should you be creating XmlHttpRequest objects at all, when you could be concentrating on higher-level concerns?

Fortunately, Prototype includes objects and functionality that make Ajax programming quite easy. For example, last month's column showed how we could use Ajax to check whether a user name was already taken when an individual registers for a Web site, which I show in Listing 4. The idea is that when someone enters a user name, we immediately fire off a request to the server. The server's response will tell us whether the user name has been taken. We invoke our Ajax request by setting the username field's onchange event handler to invoke checkUsername:

function checkUsername() {
    // Send the HTTP request
xhr.open("POST", "/cgi-bin/check-name-exists.pl", true);
xhr.onreadystatechange = parseResponse;

var username = document.forms[0].username.value;
    xhr.send("username=" + escape(username));
}

Unfortunately, getting to this point requires that we have already defined xhr to be an instance of our XmlHttpRequest object, which we do as follows:

function getXMLHttpRequest () {
    try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {};
    try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
    try { return new XMLHttpRequest(); } catch(e) {};
    return null;
}

    var xhr = getXMLHttpRequest();

Prototype can remove much of the previous code, making it possible not only to reduce the clutter in our Web pages, but also to think at a higher level of abstraction. Just as text processing becomes easier when we think about strings rather than bits and characters, Ajax development becomes easier when we no longer need to worry about instantiating various objects correctly or keep track of their values.

We can rewrite checkUsername to take advantage of Prototype as follows:

function checkUsername()
{
    var url =
"http://www.lerner.co.il/cgi-bin/check-name-exists.pl";

var myAjax = new Ajax.Request(
    url,
    {
        method: 'post',
        parameters: $F("username"),
        onComplete: parseResponse
    });
}

In the above function, we define two variables. One of them, url, contains the URL of the server-side program to which our Ajax request will be submitted. The second variable is myAjax, which is an instance of Ajax.Request. When we create this object, we pass it our url variable, as well as an object in JSON (JavaScript Object Notation) format. This second parameter tells the new Ajax.Request object what request method and parameters to pass, as well as what function to invoke upon a successful return.

It might seem as though we have simply rewritten the original version of checkUsername. But, when you consider the changes we now can make to parseResponse, you'll see how much simpler Prototype makes our lives:

function parseResponse(originalRequest) {

    var response = originalRequest.responseText;
    var new_username = $F("username");
    var warning = $("warning");
    var submit_button = $("submit-button");

switch (response)
{
case "yes":
    setText(warning,
        "Warning: username '" +
        new_username +"' was taken!");
    submit_button.disabled = true;
    break;

case "no":
    removeText(warning);
    submit_button.disabled = false;
    break;

case "":
    break;

default:
    alert("Unexpected response '" + response + "'");
}
}

The resulting rewrite of our program, post-ajax-register.html, is shown in Listing 5, ajax-register-prototype.html. It uses a number of features of Prototype, from simple ones, such as $(), to the Ajax request. We no longer need to wait for the response to arrive in its complete form; now we can let Prototype do the heavy lifting.

______________________

Geek Guide
The DevOps Toolbox

Tools and Technologies for Scale and Reliability
by Linux Journal Editor Bill Childers

Get your free copy today

Sponsored by IBM

Webcast
8 Signs You're Beyond Cron

Scheduling Crontabs With an Enterprise Scheduler
On Demand
Moderated by Linux Journal Contributor Mike Diehl

Sign up now

Sponsored by Skybot