Defining Ajax with simple exaple Ajax isn�t a technology.

It�s really several technologies, each flourishing in its own right, coming together in powerful new ways. Ajax incorporates: * standards-based presentation using XHTML and CSS; * dynamic display and interaction using the Document Object Model; * data interchange and manipulation using XML and XSLT; * asynchronous data retrieval using XMLHttpRequest; * and JavaScript binding everything together. Remote Scripting Using XMLHttpRequest Although XMLHttpRequest is not a public standard, most modern browsers implement it consistently, and it's well on its way to becoming a de facto standard for JavaScript data retrieval. Internet Explorer 5 for Windows, Mozilla 1.0, Safari 1.2 and the upcoming version 8.0 of Opera all introduce XMLHttpRequest as an available object. If you require support for browsers that are older than these, methods using iframes provide a viable solution; however, coding for these browsers will also limit your ability to utilize standard JavaScript DOM methods. This article will focus on the more contemporary XMLHttpRequest method. Creating an XMLHttpRequest Object For any browser, except Internet Explorer, we can create an XMLHttpRequest object like this: var requester = new XMLHttpRequest(); However, in Internet Explorer, XMLHttpRequest is implemented as an ActiveX object. For IE, an object is created like this: var requester = new ActiveXObject("Microsoft.XMLHTTP"); Note: this also means that if users have ActiveX objects disabled in Internet Explorer, they will be unable to use XMLHttpRequest even if JavaScript is enabled. To cope with the differences in object creation syntax used by these browsers, it's best to use a try/catch structure to automatically provide you with the correct object, or return an error if the XMLHttpRequest object is not available: try { var requester = new XMLHttpRequest(); } catch (error) { try { var requester = new ActiveXObject("Microsoft.XMLHTTP"); } catch (error) { return false; } }

Thankfully, the difference between implementations ends there, and all subsequent method calls to the XMLHttpRequest object can be performed irrespective of which browser the script's running in. Transporting Data using an XMLHttpRequest Object Once an XMLHttpRequest object has been created, we must call two separate methods in order to get it to retrieve data from a server. open() initialises the connection we wish to make, and takes two arguments, with several optionals. The first argument is the type of request we want to send; the second argument identifies the location from which we wish to request data. For instance, if we wanted to use a GET request to access feed.xml at the root of our server, we'd initialise the XMLHttpRequest object like this:"GET", "/feed.xml"); The URL can be either relative or absolute, but due to cross-domain security concerns, the target must reside on the same domain as the page that requests it. The open() method also takes an optional third boolean argument that specifies whether the request is made asynchronously (true, the default) or synchronously (false). With a synchronous request, the browser will freeze, disallowing any user interaction, until the object has completed. An asynchronous request occurs in the background, allowing other scripts to run and letting the user continue to access their browser. It's recommended that you use asynchronous requests; otherwise, we run the risk of a user's browser locking up while they wait for a request that went awry. open()'s optional fourth and fifth arguments are a username and password for authentication when accessing a password-protected URL. Once open() has been used to initialise a connection, the send() method activates the connection and makes the request. send() takes one argument, allowing us to send extra data, such as CGI variables, along with the call. Internet Explorer treats it as optional, but Mozilla will return an error if no value is passed, so it's safest to call it using: requester.send(null); To send CGI variables using the GET request method, we have to hardcode the variables into the open() URL:"GET", "/"); requester.send(null); To send CGI variables using the POST request method, the CGI variables can be passed to the send() method like so:"POST", "/"); requester.send("name=Bob&"); Once we've called send(), XMLHttpRequest will contact the server and retrieve the data we requested; however, this process takes an indeterminate amount of time. In order to find out when the object has finished retrieving data, we must use an event listener. In the case of an XMLHttpRequest object, we need to listen for changes in its readyState variable. This variable specifies the status of the object's connection, and can be any of the following:

0 1 2 -

uninitialized Loading loaded -

Object is not initialized with data.

Object is loading its data. Object has finished loading its data.

3 - interactive - User can interact with the object even though it is not fully loaded. 4 - complete - Object is completely initialized. Changes in the readyState variable can be monitored using a special onreadystatechange listener, so we'll need to set up a function to handle the event when the readyState is changed: requester.onreadystatechange = stateHandler; SITEPOINT BOOKS "The JavaScript Anthology: 101 Essential Tips, Tricks & Hacks" Photo of Cameron and James by James Edwards & Cameron Adams Follow two of the world�s most innovative JavaScript virtuosos as they walk you through over 100 modern, best practice, JavaScript solutions. This book will change the way you use JavaScript. readyState increments from 0 to 4, and the onreadystatechange event is triggered for each increment, but we really only want to know when the connection has completed (4), so our handling function needs to realise this. Upon the connection's completion, we also have to check whether the XMLHttpRequest object successfully retrieved the data, or was given an error code, such as 404: "Page not found". This can be determined from the object's status property, which contains an integer code. "200" denotes a successful completion, but this value can be any of the HTTP codes that servers may return. If the request was not successful, we must specify a course of action for our program: function stateHandler() { if (requester.readyState == 4) { if (requester.status == 200) { success(); } else { failure(); } } return true; } Even though the XMLHttpRequest object allows us to call the open() method multiple times, each object can really only be used for one call, as the onreadystatechange event doesn't update again once readyState changes to "4" (in Mozilla). Therefore, we have to create a new XMLHttpRequest object every time we want to make a remote call.

Parsing the Data in an XMLHttpRequest Object If we've made a successful request, two properties of the XMLHttpRequest object may contain data: * responseXML stores a DOM-structured object of any XML data that was retrieved by the object. This object is navigable using the standard JavaScript DOM access methods and properties, such as getElementsByTagName(), childNodes[ ] and parentNode. * responseText stores the data as one complete string. If the content type of the data supplied by the server was text/plain or text/html, then this is the only property that will contain data. A copy of any text/xml data will be flattened and placed here as an alternative to responseXML. Depending upon the complexity of the data, it may be easier to return data simply as a plain text string, thereby making the XML in XMLHttpRequest redundant. However, for more complex data types, you'll probably want to use an XML format, such as this: <?xml version="1.0" ?> <user> <name>John Smith</name> <email></email> </user> We are able to access different parts of the data using standard DOM access methods. Remember that data contained between tags is considered to represent child text nodes of the parent, so we have to take that extra layer of structure into account when we retrieve the data: var nameNode = requester.responseXML.getElementsByTagName("name")[0]; var nameTextNode = nameNode.childNodes[0]; var name = nameTextNode.nodeValue; We must also be careful about whitespace: indenting values in the XML file may produce unwanted whitespace in the value, or add additional text nodes. Once we've parsed the data from the XMLHttpRequest object, we're free to change, delete and write it onto our Web page as we see fit!