This page shows the basic code to make AJAX requests using the XHR object. An AJAX request is a type of RPC to a server process that then displays the returned results in a browser without refreshing the page. Client data maybe sent with the request, and the returned content may be in the form of an XML document or, more commonly, a string.
This requires skill in DTHML, Javascript, and a server-side language (any CGI or scripting language will do).
The benefit is a better user experience due to improved performance
Here is the basic code to create an instance of the xmlHttpRequest object. This or something very much like it is used throughout the AJAX or XHR examples on this site and many other site on the internet.
function createXHR() { var xhrObj; if (window.XMLHttpRequest) { // branch for native XMLHttpRequest object - Mozilla, IE7 try { xhrObj = new XMLHttpRequest(); } catch (e) { xhrObj = null; } } else if (window.createRequest) { /* For ICEbrowser -- untested. * per their site * http://support.icesoft.com/jive/entry.jspa?entryID=471&categoryID=21 */ try { xhrObj = window.createRequest(); } catch (e) { xhrObj = null; } } else if (window.ActiveXObject) { // branch for IE/Windows ActiveX version try { xhrObj = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { try{ xhrObj = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { xhrObj = null; } }//catch } //if-else return xhrObj; }//eof createXHR
The code is fairly straight forward. It checks which of three mechanisms the browser supports and then attempts to create an object instance. Each attempt is bracketed by try-catch structure to gracefully catch errors. In the case of IE versions 6.x and 5.x, the attempts bounce through possible activeX methods. The XHR object or null is returned.
Next is a basic method to create a GET call once the object is created is next.
var xhrObj = createXHR(); //global function makeRequest(url) { if (xhrObj) { try { xhrObj.open("GET", url, true); xhrObj.onreadystatechange = callback_function; xhrObj.send(null); } catch (e) { //Handle error } } else { //do plan B. You do have a plan B, no? } }
Some examples on the internet assign the callback function to the onreadystatechange event before calling the open method. This is incorrect; although, it generally works. In IE, if the readyState value is 1, 2, or 3, calling open clears the event handler. This can occur when a single XHR object is being reused and the previous request has not completed. Then there won't be a registered handler for the current request.
The try-catch structure traps errors thrown by Firefox when the XHR object is currently processing a request.
Note:
var xhrObj = createXHR(); //global function makeRequest(url) { if (xhrObj) { try { xhrObj.open("POST", url, true); xhrObj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhrObj.onreadystatechange = callback_function; xhrObj.send(dataStringToSend); } catch (e) { //Handle error } } else { //do plan B. You do have a plan B, no? } }
A POST request differs from a GET by passing the data being put as an agrument to the send method, using "POST" in the open method, and setting the request header. If the Content-Type header is not set the server will discard the post data.
The post data is in name value pair format; e.g., "field1=john&field2=Jones&so=on".
function callback() { if (xhrObj.readyState == 4) { try { if (xhrObj.status == 200) [code to handle returned data] //string data is accessed xhrObj.responseText //XML document is accessed xhrObj.responseXML and then DOM methods used //for example var xmlDoc = xhrObj.responseXML; var nameList = xmlDoc.getElementsByTagName("name"); else alert("Status error"); } catch (e) { alert("Server Error"); } } }
The callback function is straightforward. Ready state values are 0, 1, 2, 3, and 4. Once the readystate is completed (4), the HTTP status is checked. A status of 200 is ok and the data can be processed.
String data is returned in the xmlHttpRequest object's responseText property. XML documents are returned in the responseXML property.
A try-catch block is used in the callback function to trap errors thrown by Firefox. Firefox will throw and error if the status has not been returned; e.g., a server error, aborted process, or having the default form action or href call run at the same time as the AJAX request.
The above patterns work with a global xmlHttpRequest (XHR) object. The following pattern using a local XHR object, an anonymous function to bind the handler, and a closure allows simultaneous requests.
function makeRequest(url) { var xhrObj = createXHR(); if (xhrObj) { try { xhrObj.open("GET", url, true); xhrObj.onreadystatechange = function (){callback_function(xhrObj);}; xhrObj.send(null); } catch (e) { //Handle error } } else { //do plan B. You do have a plan B, no? } } function callback(xhr) { if (xhr.readyState == 4) { try { if (xhr.status == 200) [code to handle returned data] else alert("Status error"); } catch (e) { alert("Server Error"); } } }
if (xhrObj) { try { xhrObj.open("GET", url, true); if (xhrObj.overrideMimeType) { xhrObj.overrideMimeType('text/xml'); //Firefox & Safari } xhrObj.onreadystatechange = callback_function; xhrObj.send(null); } catch (e) { //Handle error } } else { //do plan B. You do have a plan B, no? }
The line xhrObj.overrideMimeType('text/xml');
,
which is not supported in IE, will make sure
the returned data is treated as XML. However, if the returned data
is not valid XML an error will be thrown,
at least in later versions of Firefox.
The server should set the response header for the content-type.
For example, using PHP the line would be:
header('Content-Type: text/xml');
The returned XML has the following format.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <root> <name>John Jones</name> </root>
The following code fragments demonstrate the HTML for AJAX calls. Note, however, that in-line attachment of the event handler is shown only for simplicity of presentation. A better practice is to use script to attach the handler either as a property of the HTML Element or use a binding function. More information can be found in the tutorial Binding Event Handlers.
<a href="plan-b.php" onclick="return makeRequest('ajax.php');">link word</a> <form action="plan-b.php" method="POST" onsubmit="return makeRequest('ajax.php');">
The event handler, makeRequest, prevents the default action if the XHR object can be created; otherwise it lets the default action occure; i.e., plan-b is followed. See Binding Event Handlers: Preventing Default Action for more information.
That's the basics of the xmlHttpRequest object. Checkout some of the other pages on this site and the internet for different variation for specific purposes