Ajax Application Design
Last month's version of the program sent a GET request. It is possible, and even common, to send one or more parameters with a GET request. Those parameters are then stuck onto the URL, as follows: http://www.example.com/foo.pl?param1=value1¶m2=value2.
A separate type of request, known as POST, puts the parameters inside of the request body. This has several advantages, including cleaner URLs and no limit on the length of the parameter names and values. (Many browsers limit the total size of a URL, which includes the parameters for a GET request.)
Although it is not strictly necessary for us to use a POST request for this example program, it is good to see how we can pass parameters in our request. And indeed, it is quite easy to do so. Compare the following code (taken from Listing 2) with the similar excerpt above (from Listing 1):
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));
}
As you can see, we have changed the first two parameters to xhr.open to be POST (instead of GET) and to point to a program that will generate dynamic output. The third parameter, which tells the XMLHttpRequest object that it should make the query in the background (that is, asynchronously), remains set to true. I also changed the name of the callback routine to parseResponse, from parseUsername.
The other change is that we are now sending parameters to the server. The variable queryString is just a string consisting of name-value pairs, in the traditional Web format of:
param1=value1¶m2=value2
We thus build such a query string, and send it to the server.
Listing 2. 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>
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 |
- RSS Feeds
- Dynamic DNS—an Object Lesson in Problem Solving
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Using Salt Stack and Vagrant for Drupal Development
- New Products
- A Topic for Discussion - Open Source Feature-Richness?
- Drupal Is a Framework: Why Everyone Needs to Understand This
- Validate an E-Mail Address with PHP, the Right Way
- What's the tweeting protocol?
- Tech Tip: Really Simple HTTP Server with Python
- Kernel Problem
2 hours 3 min ago - BASH script to log IPs on public web server
6 hours 30 min ago - DynDNS
10 hours 6 min ago - Reply to comment | Linux Journal
10 hours 38 min ago - All the articles you talked
13 hours 2 min ago - All the articles you talked
13 hours 5 min ago - All the articles you talked
13 hours 6 min ago - myip
17 hours 31 min ago - Keeping track of IP address
19 hours 22 min ago - Roll your own dynamic dns
1 day 35 min 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));