Writing Web Applications with Web Services and Ajax
Listing 3. JavaScript code handles the database actions and data processing.
var req;
function insert_record () {
send_transaction("/cgi-bin/insert.pl");
return 1;
}
function select_record (i) {
send_transaction("/cgi-bin/select.pl?id=" + i);
return 1;
}
function delete_record (i) {
send_transaction("/cgi-bin/delete.pl?id=" + i);
var id = document.getElementById("id");
select_record(id);
return;
}
function update_record (i, field, value) {
send_transaction("/cgi-bin/update.pl?id=" + i +
"&field=" + field + "&value=" + value);
return 1;
}
function send_transaction (i) {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req) {
req.onreadystatechange = process_results;
req.open("GET", i, true);
req.send(null);
}
}
function process_results () {
var name = "";
var value = "";
var fields;
var i;
var length;
if (req.readyState < 4) { return 1; } // transaction
// not done, yet
var xml = req.responseXML;
var result = xml.getElementsByTagName("result").item(0);
fields = result.getElementsByTagName("field");
length = fields.length;
for (i=0; i<length; i++) {
var field = fields[i];
name = field.getAttribute("name");
value = field.getAttribute("value");
var form_field = document.getElementById(name);
form_field.value = value;
}
return 1;
}
The insert_record() JavaScript function, which is called when a user presses the New button, is the simplest of the JavaScript functions. All insert_record() does is use the send_transaction() function to call the insert.pl Web Service. In fact, the insert_record(), delete_record(), select_record() and update_record() functions are all wrappers for send_transaction().
The send_transaction() function is where the Ajax comes into our application. This function takes the URL of the service that needs to be called as well as any parameters that need to be passed to the service via HTTP's GET method. Then, the function creates an object that allows the service to be called. We have to jump through a small hoop, because Microsoft chose to call this object ActiveXObject while almost every other browser calls it XMLHttpRequest. Once the object is created, by whatever name, we tell the object to call our Web Service and then call our process_results() function when the call has returned its results. This is done in the line that assigns the function name to the object's onreadystatechange property.
Well, I lied a little bit. It turns out that the browser will call our process_results() function up to four times at various stages during the service request. Each time the function is called, the value of the readyState property is changed to reflect what phase of the transaction is occurring. Unfortunately, there doesn't seem to be much agreement on when the function is called. The only thing that all browsers seem to agree on is that when the transaction is complete, the readyState property is set to 4. Checking for this value is the first thing our process_results() function does. If the transaction isn't complete, we simply return quietly.
Once the transaction is complete, we can recover the resulting XML from the request object's responseXML property. Once we have the XML, we loop over each field element, making a note of both the field name and value. Then we find the corresponding field in the HTML document and assign the new value to it. So by sending the appropriate XML, the Web Services can arrange for any, or all, of the Web form fields to be updated.
If you think the JavaScript was easy to follow, wait until you see the Perl scripts that implement the Web Services; they're even easier to understand and debug. The insert.pl program is shown in Listing 4.
Listing 4. The server-side Perl script handles the database insert action.
#!/usr/bin/perl
use DBI;
$dbh = DBI->connect("dbi:Pg:dbname=database",
↪"postgres", "password");
$dbh->do("insert into contacts (first,last,phone) values
(NULL,NULL,NULL)");
$sth = $dbh->prepare("select last_value from
↪contacts_id_seq");
$sth->execute();
($index) = $sth->fetchrow_array();
print "Content-type: text/xml\n\n\n";
print "<result>\n";
print "<field name=\"id\" value=\"$index\"></field>\n";
print "</result>\n";All this program does is connect to a database, insert an empty record into the contacts table, retrieve the id of the newly created record and return the results in a block of XML with a text/xml MIME type. The resulting XML resembles that shown in Listing 5.
Mike Diehl is a freelance Computer Nerd specializing in Linux administration, programing, and VoIP. Mike lives in Albuquerque, NM. with his wife and 3 sons. He can be reached at mdiehl@diehlnet.com
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)
- Drupal Is a Framework: Why Everyone Needs to Understand This
- A Topic for Discussion - Open Source Feature-Richness?
- RSS Feeds
- Home, My Backup Data Center
- What's the tweeting protocol?
- Readers' Choice Awards 2011
- Linux on Azure—a Strange Place to Find a Penguin
- Developer Poll
- Reply to comment | Linux Journal
4 hours 2 min ago - Reply to comment | Linux Journal
6 hours 35 min ago - Reply to comment | Linux Journal
7 hours 52 min ago - great post
8 hours 27 min ago - Google Docs
8 hours 49 min ago - Reply to comment | Linux Journal
13 hours 38 min ago - Reply to comment | Linux Journal
14 hours 25 min ago - Web Hosting IQ
15 hours 59 min ago - Thanks for taking the time to
17 hours 35 min ago - Linux is good
19 hours 33 min ago
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.




Comments
Lob
thx for the great stuff
Thanks
This helps me a whole bunch with a little project I'm working on!