Here is a paper by one of the earlier adopters of AJAX: AJAX: A New Approach to Web Applications by Jesse James Garrett.
Create a new XMLHttpRequest Object
<script type = "text/javascript">
var xhr;
if (window.ActiveXObject) {
xhr = new ActiveXObject ("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest ();
}
}
</script>
Get and set values using JavaScript
// Get the value of the "name" field and assign it to a variable called name
var name = document.getElementById("name").value;
// Set the values on a form using an array called result
document.getElementById("ssn").value = result[0];
Start an AJAX call
<form>
<p>State: <input type = "text" name = "state" size = "25"
onChange = "callServer();" /> </p>
</form>
Make an AJAX Request Using GET
function callServer() {
// Get city and state from web form
var city = document.getElementById("city").value;
var state = document.getElementById("state").value;
// Only make the server call if there is data
if ((city == null) || (city == "")) return;
if ((state == null) || (state == "")) return;
// Build the URL to connect to
var url = "/scripts/getZipCode.php?city=" + escape(city) +"&state=" + escape(state);
// Open a connection to the server
xhr.open ("GET", url, true);
// Setup a function for the server to run when it is done
xhr.onreadystatechange = updatePage;
// Send the request
xhr.send(null);
}
The escape() method is used to escape any characters like spaces that cannot be sent
as clear text correctly.
Make an AJAX Request Using POST
function callServer() {
// Get city and state from web form
var city = document.getElementById("city").value;
var state = document.getElementById("state").value;
// Only make the server call if there is data
if ((city == null) || (city == "")) return;
if ((state == null) || (state == "")) return;
// Build the URL to connect to
var url = "/scripts/getZipCode.php";
// Create the name-value pairs that will be sent as data
var params = "cityName=city&stateName=state";
// Open a connection to the server
xhr.open ("POST", url, true);
// Create the proper headers to send with the request
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", params.length);
xhr.setRequestHeader("Connection", "close");
// Setup a function for the server to run when it is done
xhr.onreadystatechange = updatePage;
// Send the request
xhr.send(params);
}
Handle the Server Response
function updatePage() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var response = xhr.responseText;
document.getElementById("zipCode").value = response;
}
}
}
We have created a simple AJAX application that illustrates the basic concepts. This application is a Pizza Ordering Form. There are various inputs in this ordering form, the first of which is the phone number of the customer. The Pizza Company keeps a database of all the customers who have ordered before. As soon as the customer types in his / her phone number a call is made to the server to search the database for that phone number and extract all the relevant information on that client. That information is then used to auto fill the form. Here is the table that has been created in the database:
Phone | Last Name | First Name | Street | City | State | Zip |
407-896-0001 | Mouse | Mickey | 123 Cheddar St. | Orlando | FL | 32801 |
407-896-0002 | Duck | Donald | 387 Eider Dn. | Orlando | FL | 32801 |
407-896-0003 | Mouse | Minnie | 482 Brie Ln. | Orlando | FL | 32801 |
Here is the Pizza Ordering Form. The JavaScript code that forms the core of the AJAX application and the PHP code to extract data from the database are not robust nor secure. We have taken the happy path in this example to illustrate how AJAX works and not clutter the application with error handling code.
XML is neither necessary nor required to make requests to the server. In fact it is less efficient than sending data in plain text as name-value pairs. The only compelling reason to use the XML format in sending requests is that the script on the server side does not accept data in any other format. Here is an example of how to send a request in XML format:
Let us say that the server only accepts a person's name in this format: <name> <firstName> Mickey </firstName> <lastName> Mouse </lastName> </name> Then these steps have to be followed to send a person's name to the server: function callServer() { // Get the first and last name from the form var firstName = document.getElementById("firstName").value; var lastName = document.getElementById("lastName").value; // Create the XML String var xmlStr = "<name>" + "<firstName>" + escape(firstName) + "</firstName>" + "<lastName>" + escape(lastName) + "</lastName>" + "</name>"; // Build the URL to connect to var url = "/scripts/accessNames.php"; // Open a connection to the server xhr.open ("POST", url, true); // Tell the server that you are sending XML xhr.setRequestHeader ("Content-Type", "text/xml"); // Delegate a function to handle the response xhr.onreadystatechange = updatePage(); // Send the request xhr.send (xmlStr); }
While it is easy to send a request as name-value pairs to the server, no matter in what format the response comes back it has to be parsed on the client side. It makes sense to send the response in as unambiguous way as possible. This where the strength of XML lies. If the response came back in the following format you would have no problem understanding what it meant:
<students> <student> <name> Mickey Mouse </name> <major> Dance </major> <gpa> 3.5 </gpa> </student> <student> <name> Donald Duck </name> <major> Song </major> <gpa> 3.2 </gpa> </student> </students>
There are two ways in which you can treat the XML response from the server:
If you treat the XML response as plain text your code in the function updatePage() to accept the response would be of the form:
var response = request.responseText;where response would be in the form of a long string with no spacings like so:
<students><student><name>Mickey Mouse</name> <major> Dance </major><gpa>3.5</gpa></student> <student><name>Donald Duck</name><major>Song</major> <gpa>3.2</gpa></student></students>The string has been split into lines for readability. You would then parse the string using the various String functions in JavaScript like split() and extract the information.
On the other hand if you treat the XML response as DOM document object then JavaScript provides utilities to parse the response more efficiently. The following example shows how:
function updatePage() { if ((request.readyState == 4) && (request.status == 200)) { var xmlDoc = request.responseXML; // Get all student elements as an array var student = xmlDoc.getElementsByTagName ("student"); // Iterate through the array and retreive the student info for (var i = 0; i < student.length; i++) { var name = student[i].childNodes[0].value; var major = student[i].childNodes[1].value; var gpa = student[i].childNodes[2].value; // Now you can do something with this data } } }
Mastering AJAX: Part 1: Introduction to AJAX by Brett McLaughlin.
Mastering AJAX: Part 2: Make Asynchronous requests with JavaScript and AJAX by Brett McLaughlin.
Mastering AJAX: Part 3: Advanced Requests and Responses in AJAX by Brett McLaughlin.
Mastering AJAX: Part 4: Exploiting DOM for Web Response by Brett McLaughlin.
Mastering AJAX: Part 5: Manipulate the DOM by Brett McLaughlin.
Mastering AJAX: Part 6: Build DOM-based Web Applications by Brett McLaughlin.
Mastering AJAX: Part 7: Using XML in Requests and Responses by Brett McLaughlin.
Mastering AJAX: Part 8: Using XML in Requests and Responses by Brett McLaughlin.
Mastering AJAX: Part 9: Using the Google Ajax Search API by Brett McLaughlin.
Mastering AJAX: Part 10: Using JSON for Data Transfer by Brett McLaughlin.
Mastering AJAX: Part 11: JSON on the Server Side by Brett McLaughlin.