Ajax Application Design

Asynchronous is the operative word with Ajax, and here's what it's all about.
Sending a POST Request

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&param2=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&param2=value2

We thus build such a query string, and send it to the server.

______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Good article

gds's picture

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));

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

Upcoming Webinar
8 Signs You're Beyond Cron

Scheduling Crontabs With an Enterprise Scheduler
11am CDT, April 29th
Moderated by Linux Journal Contributor Mike Diehl

Sign up now

Sponsored by Skybot