Ajax Application Design
Given the above list, how can we move from the simple program we wrote last month to one that will fulfill our scalability and security requirements?
When we created our simple Ajax user name-checking program in last month's column, we used two of these three elements. We created an HTML form (shown in Listing 1) that would let people register with our Web site by entering a user name, password and e-mail address. We then indicated that whenever the username text field was changed, the checkUsername JavaScript function should be invoked:
<input type="text" name="username" onchange="checkUsername()" />
checkUsername then asked our server—the same server from which the current page of HTML came—for the contents of a text file:
function checkUsername() {
// Send the HTTP request
xhr.open("GET", "usernames.txt", true);
xhr.onreadystatechange = parseUsernames;
xhr.send(null);
}
This is the first place where we will need to make a change. Rather than send a GET request without any parameters to request a static document, we will send a POST request with a single parameter (username), which will result in the execution of a server-side program.
Finally, our callback routine (parseUsernames) iterated over the list of user names that the server had sent, using the DOM to warn the user if it found a match. This is the other place where we will need to make a change. But in this case, the change will be a simplification. No longer will we need to parse through the user names sent by the server. Instead, we will need to identify only whether the response was positive or negative.
Listing 1. 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 parseUsernames() {
// Set up empty array of usernames
var usernames = [ ];
// Wait for the HTTP response
if (xhr.readyState == 4) {
if (xhr.status == 200) {
usernames = xhr.responseText.split("\n");
}
else
{
alert("problem: xhr.status = " + xhr.status);
}
}
// Get the username that the person wants
var new_username = document.forms[0].username.value;
var found = false;
var warning = document.getElementById("warning");
var submit_button = document.getElementById("submit-button");
// Is this new username already taken? Iterate over
// the list of usernames to be sure.
for (i=0 ; i<usernames.length; i++)
{
if (usernames[i] == new_username)
{
found = true;
}
}
// If we find the username, issue a warning and stop
// the user from submitting the form.
if (found)
{
setText(warning, "Warning: username '" + new_username
+"' was taken!");
submit_button.disabled = true;
}
else
{
removeText(warning);
submit_button.disabled = false;
}
}
function checkUsername() {
// Send the HTTP request
xhr.open("GET", "usernames.txt", true);
xhr.onreadystatechange = parseUsernames;
xhr.send(null);
}
</script>
</head>
<body>
<h2>Register</h2>
<p id="warning"></p>
<form action="/cgi-bin/register.pl" method="post">
<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>
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
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
| Designing Electronics with Linux | May 22, 2013 |
| Dynamic DNS—an Object Lesson in Problem Solving | May 21, 2013 |
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| 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 |
- Designing Electronics with Linux
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Dynamic DNS—an Object Lesson in Problem Solving
- Using Salt Stack and Vagrant for Drupal Development
- New Products
- Validate an E-Mail Address with PHP, the Right Way
- Build a Skype Server for Your Home Phone System
- Why Python?
- A Topic for Discussion - Open Source Feature-Richness?
- Tech Tip: Really Simple HTTP Server with Python
- Great
3 hours 39 min ago - Reply to comment | Linux Journal
3 hours 47 min ago - Understanding the Linux Kernel
6 hours 2 min ago - General
8 hours 31 min ago - Kernel Problem
18 hours 34 min ago - BASH script to log IPs on public web server
23 hours 1 min ago - DynDNS
1 day 2 hours ago - Reply to comment | Linux Journal
1 day 3 hours ago - All the articles you talked
1 day 5 hours ago - All the articles you talked
1 day 5 hours ago
Enter to Win an Adafruit Pi Cobbler Breakout 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 Pi Cobbler Breakout 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
- 5-21-13, Prototyping Pi Plate Kit: Philip Kirby
- Next winner announced on 5-27-13!
Free Webinar: Hadoop
How to Build an Optimal Hadoop Cluster to Store and Maintain Unlimited Amounts of Data Using Microservers
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Some of key questions to be discussed are:
- What is the “typical” Hadoop cluster and what should be installed on the different machine types?
- Why should you consider the typical workload patterns when making your hardware decisions?
- Are all microservers created equal for Hadoop deployments?
- How do I plan for expansion if I require more compute, memory, storage or networking?




Comments
Good article
Really good articles on ajax fundamentals. One comment I have is that it is not pointed out in Part 2 and 3 that the database access, register.pl, is still in effect. It is also easy to change check-name-exists.pl above to use similar database methods as register.pl users:
#!/usr/bin/perl
use strict;
use diagnostics;
use warnings;
use CGI;
use CGI::Carp;
use DBI;
# ------------------------------------------------------------
# # Connect to the database
# ------------------------------------------------------------
my $dbname = 'test';
my $dbuser = 'gene';
my $dbpassword = '';
my $dbh = DBI->connect("DBI:mysql:dbname=$dbname",
$dbuser, $dbpassword,
{
AutoCommit => 1, RaiseError => 1,
PrintError => 1, ChopBlanks => 1}) ||
print "Error connecting: '$DBI::errstr' ";
# Define the usernames that are taken
# (Use a hash for lookup efficiency)
#my %usernames = ('abc' => 1,
# 'def' => 1,
# 'ghi' => 1,
# 'jkl' => 1);
# ------------------------------------------------------------
my $query = new CGI;
print $query->header("text/plain");
# Get the POST data
my $postdata = $query->param("POSTDATA");
# Get the username
my ($name, $value) = split /=/, $postdata;
my $username = '';
if ($name eq 'username')
{
$username = $value;
}
my $select_sql = "SELECT COUNT(*) FROM Users WHERE username = ?";
my $select_sth = $dbh->prepare($select_sql);
$select_sth->execute($username);
my ($username_is_taken) = $select_sth->fetchrow_array();
# If this username is defined, say "yes"!
if ($username_is_taken)
{
print "yes";
}
# Otherwise, say "no"!
else
{
print "no";
}
I also change it to use onblur instead of onchange but had to pass a parameter to checkUserName():
function checkUsername(val) {
:
var username = val; //document.forms[0].username.value;
xhr.send("username=" + escape(username));