At the Forge - Prototype
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?
Listing 4. post-ajax-register.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>Register</title>
<script type="text/javascript">
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;
}
function removeText(node) {
if (node != null)
{
if (node.childNodes)
{
for (var i=0 ; i < node.childNodes.length ; i++)
{
var oldTextNode = node.childNodes[i];
if (oldTextNode.nodeValue != null)
{
node.removeChild(oldTextNode);
}
}
}
}
}
function appendText(node, text) {
var newTextNode = document.createTextNode(text);
node.appendChild(newTextNode);
}
function setText(node, text) {
removeText(node);
appendText(node, text);
}
var xhr = getXMLHttpRequest();
function parseResponse() {
// Get variables ready
var response = "";
var new_username = document.forms[0].username.value;
var warning = document.getElementById("warning");
var submit_button = document.getElementById("submit-button");
// Wait for the HTTP response
if (xhr.readyState == 4) {
if (xhr.status == 200) {
response = xhr.responseText;
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 + "'");
}
}
else
{
alert("problem: xhr.status = " + xhr.status);
}
}
}
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));
}
</script>
</head>
<body>
<h2>Register</h2>
<p id="warning"></p>
<form action="/cgi-bin/register.pl" method="post"
enctype="application/x-www-form-urlencoded">
<p>Username: <input type="text" name="username"
onchange="checkUsername()" /></p>
<p>Password: <input type="password" name="password" /></p>
<p>E-mail address: <input type="text" name="email_address" /></p>
<p><input type="submit" value="Register" id="submit-button"
/></p>
</form>
</body>
</html>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.
Today’s modular x86 servers are compute-centric, designed as a least common denominator to support a wide range of IT workloads. Those generic, virtualized IT workloads have much different resource optimization requirements than hyperscale and cloud applications. They have resulted in a “one size fits all” enterprise IT architecture that is not optimized for a specific set of IT workloads, and especially not emerging hyperscale workloads, such as web applications, big data, and object storage. In this report, you will learn how shifting the focus from traditional compute-centric IT architectures to an innovative disaggregated fabric-based architecture can optimize and scale your data center.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
| Non-Linux FOSS: Seashore | May 10, 2013 |
| Trying to Tame the Tablet | May 08, 2013 |
| Dart: a New Web Programming Experience | May 07, 2013 |
- New Products
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- A Topic for Discussion - Open Source Feature-Richness?
- Drupal Is a Framework: Why Everyone Needs to Understand This
- Home, My Backup Data Center
- What's the tweeting protocol?
- Readers' Choice Awards
- New Products
- RSS Feeds
- Dart: a New Web Programming Experience
Enter to Win an Adafruit Prototyping Pi Plate Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Prototyping Pi Plate Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- Next winner announced on 5-21-13!
Free Webinar: Linux Backup and Recovery
Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.
In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.




9 hours 50 min ago
12 hours 23 min ago
13 hours 40 min ago
14 hours 15 min ago
14 hours 38 min ago
19 hours 26 min ago
20 hours 13 min ago
21 hours 47 min ago
23 hours 23 min ago
1 day 1 hour ago