Lesson 18: Making AJAX Calls

By Maria Antonietta Perna

One core feature of 21st century web applications is their fantastic responsiveness. A pioneer in the business of making the web more and more similar to a desktop application has been Google: as soon as you start typing a character in a Google box, all kinds of suggestions and search results keep popping up to speed up your search; and again, just type something using Google maps, and you're instantly catapulted to almost any street on the planet.

Behind this amazing feat of human cleverness is the coming together of a few technologies collectively known as AJAX.

In this lesson you will learn:

  • what AJAX stands for and what it is all about;
  • how to make an AJAX request;
  • how to handle an AJAX response.

I recommend you get access to a web server to carry out the example code illustrated in this lesson. In fact, AJAX is all about client-server communication. In view of this, you can upload your files to a hosted server or to a local server. The PHP tutorial on this website provides an excellent guide on this topic.

What's AJAX all about?

The acronym AJAX stands for Asynchronous JavaScript And XML.

In actual fact, it's a combination of internet standards made up of:

  • standards-based presentation using HTML and CSS;
  • dynamic display using the DOM;
  • data interchange and manipulation using XML;
  • asynchronous data retrieval using the XMLHttpRequest object;
  • JavaScript magic to orchestrate the whole process.

In non-AJAX web applications, the interaction between servers and clients can be a tedious business:

  1. a user action from the client sends a request to the web server via HyperText Transfer Protocol (HTTP);
  2. the web server receives the request and processes it by invoking server-side scripts, database data, etc., and sends a response back to the client via HTTP;
  3. the client browser receives the response and loads the entire updated page.

Having to go from browser to server and back again each time a user requests some piece of data from the server, in addition to undergoing an entire page refresh at each update, can be quite stressful on servers and on users alike.

AJAX helps in at least 2 respects: piecemeal page updates and asynchronous communication between server and client.

What this means in a few words, is that every time the user interacts with the web page, only those bits that need updating are refreshed, not the entire page. Furthermore, the fact that AJAX operations are performed asynchronously, means that during the time that it takes for the server to respond, the page is not locked and the user can still interact with the website.

How do I make an AJAX request?

An AJAX request is made using the XMLHttpRequest object and its open() and send() methods. This is supported by all major browsers. However, older browsers, namely older varsions of Microsoft Internet Explorer (vesions 5 and 6), support an ActiveXObject. This little hurdle is easily overcome by testing for feature support in the script.

The open(retrievalMethod, url, bool) method has 3 arguments:

  1. retrievalMethod: this can either be a GET (used to fetch data from the server), or a POST (used to send data to the server);
  2. url: this is the location where the data is made available. It can be a text file, an XML document, or a server-side script that processes data coming from a database;
  3. bool: this is a true/false value. If it's false the request is made synchronously, if it's true the request is made asynchronously, which is what we usually want.

The XMLHttpRequest object has an onreadystatechange property that deals with the response from the server. This proceeds over the following 5 stages:

  • 0) the request is uninitialized because open() has not been called;
  • 1) the request is specified, but send() has not been called yet;
  • 2) the request is being sent, because now send() has been called;
  • 3) the response is being received, but not yet completed;
  • 4) the response is complete and data is available for manipulation and display.

Upon completion (stage 4), the XMLHttpRequest object's status property gets assigned an HTTP status code that describes the result of the request as follows:

  • 200: success!
  • 401: unauthorized - authentication is required and was not provided;
  • 403: forbidden - the server refuses to respond;
  • 404: not found - the requested resource cannot be found.

This is a simple code snippet that translates what's just been said into practice:

		
		//Global variable to store the XMLHttpRequest object
		
		var myRequest;
		
		//Package the request into its own function
		
		function getData()
		
		{
		
		//Feature-testing technique to make sure the browser
		
		//supports the XMLHttpRequest object
		
		if (window.XMLHttpRequest)
		
		{
		
		//create a new instance of the object
		
		myRequest = new XMLHttpRequest();
		
		}
		
		//else - the XMLHttpRequest object is not supported:
		
		//create an instance of ActiveXObject
		
		else
		
		{
		
		myRequest = new ActiveXObject("Microsoft.XMLHTTP");
		
		}
		
		//Use the open(retrievalMethod, "myDataFile.txt", bool) method
		
		myRequest.open("GET", url, true);
		
		//Use send() with a null argument - we have nothing to send:
		
		myRequest.send(null);
		
		//attach a function to handle onreadystatechange,
		
		//that is, the response from the server:
		
		myRequest.onreadystatechange = getData;
		
		}
		
		

How do I handle the AJAX response?

If the client browser requests text data, the server response is automatically stored in the responseText property.

If the client browser requests data in XML format, the server response is stored in the responseXML property.

Here's a code snippet that illustrates this in practice.

		
		//Package the response-handling code in a function
		
		function getData()
		
		{
		
		//Make sure the response is at the completion stage (4):
		
		if (myRequest.readyState ===4)
		
		{
		
		//if it is, make sure the status code is 200 (success):
		
		if (myRequest.status === 200)
		
		{
		
		//if all is well, handle the response:
		
		var text = myRequest.responseText;
		
		alert(text);
		
		}
		
		}
		
		}
		
		

Let's tackle two examples that include both request and response using AJAX. The first example will be dealing with a response in plain text format, the second example with a response in XML format.

AJAX request - response example: plain text response

To follow along, you need a server and 1 simple text file uploaded to the same server that hosts your JavaScript code.

The page you're going to build allows the user to click a button to display some text stored in your text file using AJAX.

Here's a simple HTML page with a <header> tag and a button element:

		
		<!DOCTYPE html>
		<html>
		<head>
		<title>Lesson 18: Making AJAX Calls</title>
		
		</head>
		<body>
		<h1>Lesson 18: Making AJAX Calls - Plain Text Response</h1>
		
		<div>
		
		<h2 id="myHeader">Click the button to call your data</h2>
		
		<input type="button" value="Click Me!" onclick="getText('lesson18_test.txt')" />
		
		</div>
		
		<script type="text/javascript">
		
		//JavaScript AJAX code here
		
		</script>
			
		</body>
		</html>
		
		

Here's the JavaScript code that goes in enclosing <script> tags in the HTML page above:

		
		//Prepare the global variable for the request
		
		var myRequest;
		
		//Write the getText(url) function
		
		function getText(url)
		
		{
		
		//check support for the XMLHttpRequest object
		
		if (window.XMLHttpRequest)
		
		{
		
		myRequest = new XMLHttpRequest();
		
		}
		
		//else, create an ActiveXObject for IE6
		
		else
		
		{
		
		myRequest = new ActiveXObject("Microsoft.XMLHTTP");
		
		}
		
		//Call the open() method to make the request
		
		myRequest.open("GET", url, true);
		
		//Send the request
		
		myRequest.send(null);
		
		//Assign the getData() function to the
		
		//onreadystatechange property to handle server response
		
		myRequest.onreadystatechange = getData;
		
		}
		
		
		
		/**********************************************/
		
		
		
		//This function handles the server response
		
		function getData()
		
		{
		
		//Get a reference to the header element where
		
		//the returned result will be displayed
		
		var myHeader = document.getElementById("myHeader");
		
		//Check the response is complete
		
		if (myRequest.readyState ===4)
		
		{
		
		//Check the status code of the response is successful
		
		if (myRequest.status === 200)
		
		{
		
		//Store the response
		
		var text = myRequest.responseText;
		
		//Assing the returned text to the nodeValue
		
		//property of the header element (you can also use
		
		//innerHTML here if you feel it simplifies your task)
		
		myHeader.firstChild.nodeValue = text;
		
		}
		
		}
		
		}
		
		

Save your work and preview it in a browser. You should see something like the page indicated by following the example link above.

Notice how the result is returned from the server with no page flashing, no change of URL, no whole page refresh: that's the AJAX magic.

AJAX request - response example: XML format response

The page you're going to build in this second example allows the user to click a button to display a series of programming languages coming from an XML file using AJAX.

To follow along in this exercise, prepare a simple XML document and an HTML page.

Here's what my XML document looks like:

		
		<?xml version="1.0" ?>
		
		<languages>
		 <language>PHP</language>
		 <language>Ruby On Rails</language>
		 <language>C#</language>
		 <language>JavaScript</language>
		</languages>
		
		

Save the file above as lesson18_test.xml in the same location as your HTML page.

Here's the HTML page:

		
		<!DOCTYPE html>
		<html>
		<head>
		<title>Lesson 18: Making AJAX Calls</title>
		
		</head>
		<body>
		<h1>Lesson 18: Making AJAX Calls - XML Response</h1>
		
		<div id="test">
		
		<h2>Click the button to get a list of programming languages</h2>
		
		<input type="button" value="Click Me!" onclick="loadXml('lesson18_test.xml')" />
		
		</div>
		
		<script type="text/javascript">
		
		//JavaScript AJAX code here
		
		</script>
			
		</body>
		</html>
		
		

Now proceed with the JavaScript code as follows:

		
		var myRequest;
		
		//The greatest part of the loadXML() function
		
		//is similar to the previous example:
		
		function loadXML(url)
		
		{
		
		if (window.XMLHttpRequest)
		
		{
		
		myRequest = new XMLHttpRequest();
		
		}
		
		else
		
		{
		
		myRequest = new ActiveXObject("Microsoft.XMLHTTP");
		
		}
		
		myRequest.open("GET", url, true);
		
		myRequest.send(null);
		
		myRequest.onreadystatechange = getData;	
		
		}
			
		
		/******************************************/
		
		
		function getData()
		
		{
		
		//Get a reference to the div element
		
		//where the returned data will be displayed:
		
		var myDiv = document.getElementById("test");
		
		//The part of the code that checks the response
		
		//is the same as the previous example:
		
		if (myRequest.readyState ===4)
		
		{
		
		if (myRequest.status === 200)
		
		{
		
		//Use the responseXML property to catch
		
		//the returned data, select the xml tag
		
		//called language, and store returned
		
		//language items in an array variable:
		
		var languages = myRequest.responseXML.getElementsByTagName("language");
		
		//Loop over each array item containing the data
		
		//and create a <p> element to contain each returned
		
		//piece of data.  Notice the use of firstChild.data
		
		//to retrieve the value of the XML <language> tag:
		
		for (var i = 0; i < languages.length; i++)
		
		{
		
		var paragraph = document.createElement("p");
		
		myDiv.appendChild(paragraph);
		
		paragraph.appendChild(document.createTextNode(languages[i].firstChild.data));
		
		//You can also assign the returned result to myDiv.innerHTML
		
		//if you feel it would be simpler.
		
		}
		
		}
		
		}
		
		}
		
		

Save your work and preview it in a browser. You should see something like the page indicated by following the example link above.

Notice how the result is returned from the server without a whole page refresh. That's terrific!

Summary

That's it for this lesson. You worked really hard, but now you can write JavaScript code that retrieves data from the server without a whole page refresh using AJAX techniques.

You're not limited to text format files or to XML files, though. In fact, databases are the most commonly used tools to permanently store data on a server. AJAX techniques are as easily applied to deal with database retrieved information. However, you'll need PHP or a server-side programming language to retrieve data from or post data to a database.

In any case, we will return to this topic in our last lesson and see how jQuery greatly simplifies the whole Ajaxification process.

But first, we need to get some familiarity with the most popular library in the JavaScript programming world today, jQuery, which is the topic of our next lesson.


Related topics in the RepliesViews
No related topics yet

+ Post a new topic


<< Lesson 17: JavaScript Timing Events

Lesson 19: Short Introduction to jQuery >>