Warning: include(../_include/googleads.php) [function.include]: failed to open stream: No such file or directory in /www/docs/stridebird.com/articles/_showarticle.php on line 52
Warning: include() [function.include]: Failed opening '../_include/googleads.php' for inclusion (include_path='.:/usr/share/php:/usr/share/pear') in /www/docs/stridebird.com/articles/_showarticle.php on line 52
Published: 2005-08-05 12:43:59 [ previous | next | back to article list ]
AJAX basics: XMLHttpRequest
This article explains the basic principles of dynamically updating a web page using calls back to the server. The procedure forms the cornerstone of AJAX applications and the following example can be modified in myriad ways to create dynamic, interesting and user friendly web interfaces.
Step one: create XMLHttpRequest object
The first step is to create an object on the browser end that will request information from the server. To ensure cross-browser functionality, we use a function getHTTPObject() to wrap 3 possible browser methods of creating an XMLHTTP request. The section in comments is Microsoft specific 'conditional compiler' code and attempts to initialise an XMLHTTP activeX object. Other browsers will then try to initialise with their native XMLHttpRequest() method. getHTTPObject() returns an XMLHTTP request object which should be tested before use (Step two). This object will be later used to create the request.
function getHTTPObject() { var xmlhttp; /*@cc_on @if (@_jscript_version >= 5) try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { xmlhttp = false; } } @else xmlhttp = false; @end @*/ if (!xmlhttp && typeof XMLHttpRequest != 'undefined') { try { xmlhttp = new XMLHttpRequest(); } catch (e) { xmlhttp = false; } } return xmlhttp; }
Step two: initialise XMLHttpRequest object
getHTTPObject() is called to instantiate the object. This object may be re-used repeatedly depending on the page design. In this case, we create a function, requestContent(), that we can call from the event handlers of elements in the page. Each time the function is called, the http object is reset and a new request is made to the remote server.
var http = getHTTPObject(); function requestContent() { var url = "/serverside/getcontent.php"; http.open("GET", url, true); http.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); http.onreadystatechange = handleHttpResponse; http.send( null ); }
Step three: handle server response
You will have noticed above that a second function, handleHttpResponse(), has been assigned to handle the response from the remote server. Actually, it’s called on state change of the object. More info on this property. This returns “4” when the request has been completed, so handleHttpResponse() tests for request completion before trying to process the response. Other actions could be triggered on other midway states during the request - i.e. “2” : “The send method has been called, but the status and headers are not yet available” could be used to trigger display of a “Please wait while request is processed” message perhaps. In this example, we simply use a window.alert() method to display the returned text. Much more powerful options are possible, using the returned text to replace innerHTML values for elements within the DOM.
function handleHttpResponse() { if (http.readyState == 4) { var results = http.responseText; if ( results.length < 1 ) { results = ""; } alert( results ); } }
In this example we are only using http.responseText. There is another value returned, http.responseXML. This, as it implies, returns XML data and can be fed into an XML parser and further manipulated.
Step four: create server-side target
Lastly, we need a target on the server to handle the request and send back a response. In this example we are using PHP to show how easy it is to create basic server side handlers for AJAX systems.
header( "Expires: Sat, 1 Jan 2005 01:00:00 GMT" );
header( "Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );
header( "Cache-Control: no-cache, must-revalidate" );
header( "Pragma: no-cache" );
echo "Query string on request was : " . $_SERVER["QUERY_STRING"];
exit;
?>