Quick AJAX Overview
For those precious few who have held out on learning about AJAX, here is a quick overview of how to implement it.
AJAX Example
One of the first things you will need to do is to reference a function on an HTML element's event. In our example, we will use the <body> tag's onload event:
<body onload="getData();">
Next, we create the getData() function to establish the AJAX connection and retrieve the data from the server (in this case, its an XML document).
var ajax;function getData(){//Checks if it's a modern browserif(document.getElementById){//Creates the AJAX Object bases on browser typeif(window.ActiveXControl){ajax = new ActiveXOject("Microsoft.XMLHTTP");}else{ajax = new XMLHttpRequest();}//If the ajax object was created successfullyif(ajax){//Process the response (calls the processResponse function)ajax.onreadystatechange = processResponse;//XML/RSS/Web service URLajax.open("GET", "/services/data.xml", true);//Parameters to send to the URL (null in this case)ajax.send(null);}}}
If you notice, I'm using a .xml file. This could also be a web service, an rss feed, or even just a web page that returns xml.
Next, we create the "processResponse" function. In the code example above, we assign the ajax.onreadystatechange a reference to a function. This function will provide a way to access the response of the xml returned.
function processResponse(){if(ajax.readyState == 4 && ajax.status == 200){//Assign the XML returned to a local variablevar xml = ajax.responseXML;alert(xml);}}
While the above example doesn't do anything fancy, it demonstrates how easy it is to create a quick asynchronous connection to get some data without refreshing the page.
I will be creating an XMLHttpRequest tutorial in the next post, so look forward to learning more AJAX.
Adios
