Hi all, I have been learning Ajax lately and found that this is actually not a difficult technique to dive in and it is very useful for adding new web2.0 fuctions to our current sites. I have compiled the following summary to help any new developers to head start their learning of AJAX. What is AJAX AJAX stands for Asynchronous JavaScript and XML. It is actually more of a technique as it utilize the XMLHttpRequest object in the common browsers. What is AJAX used for AJAX is mainly used to load a partial webpage to display updated content rather than the conventional GET / POST methods where the whole page is reloaded. The advantage in loading a partial section of a web page is that user can still see the other content of a page while the AJAX is working. Some common applications that utilize AJAX currently is Gmail and NetFlix. An Easy Example The following example illustrate a user press a button on the form and the server will response and display the details of the newest member. You can see a live example (with a bit modification) by going to my CSS Templates site and click on the 'View all new templates'. 1st step: Creating the XMLHttpRequest Object The first step we do is to create the XMLHttpRequest Object (XHR) so that AJAX can work. The following codes are meant for creating this instance: function GetXmlHttpObject() { var objXMLHttp=null if (window.XMLHttpRequest) { objXMLHttp=new XMLHttpRequest() } else if (window.ActiveXObject) { objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP") } return objXMLHttp } Code (markup): The above function will create the XHR. The reason why there is an if loop is that some browsers do not support ActiveX objects such as Firefox, as it implements XHR as a native JavaScript object. Therefore, the above codes will cover all cases. 2nd step: Coding the main function function testajax() { xmlHttp=GetXmlHttpObject() if (xmlHttp==null) { alert ("Browser does not support HTTP Request") return } var url="pulldata.php" xmlHttp.onreadystatechange=stateChanged xmlHttp.open("GET",url,true) xmlHttp.send(null) } Code (markup): The main function will first test if the browser supports XHR, if not, end execution. We have three new properties here namely, onreadystatechange, open and send. Allow me to explain the flow: 1. The variable url, contains the URL to the file that does the processing of the queries like database abstraction. In our case, the file is coded in PHP. You can use any server-side scripting you prefer 2. onreadytstatechange will be triggered based on the application status. For example, it will trigger stateChanged() function once it has finished loading or is loading. I will explain this in the next step. 3. open will send the queries to the URL. In our case, we use the GET method to pass to the URL as stated. The true value means that this request is asynchronously. True is the default value. 4. send simply sends the request to the server. 3rd step: Detailing the stateChanged function Our stateChanged function is as follows: function stateChanged() { if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") document.getElementById("show").innerHTML=xmlHttp.responseText if (xmlHttp.readyState==1 || xmlHttp.readyState=="loading") document.getElementById("show").innerHTML="<div align=center>Loading...</div>" } Code (markup): We have two loops here. As I have mentioned before, this function will be triggered whenever the request returns a new status. In the above example, we will show the user a "Loading.." notification once the application starts loading. Upon completion of the whole request, it will display the results in the show container. 4th step: Finishing up with the Server Side Our pulldata.php looks like: <?php //select from database the latest records //save the data into the result[] //output the respective results echo'The latest member is: '.$results["name"].' '; ?> PHP: This whole string will be passed back to the client side through the responseText property and displayed in the page subsequently. Final Step: Event triggerer We will have to decide how are we going to intial this request. Is it through a form button? Or a link? I have illustrated a trigger by a press on the button below: <form action="#"> <input type="button" value="View the newest member" onclick="testajax();" /> </form> Code (markup): Putting all together In total, we have two files, our main page and the server processing file. Main File: <html> <head></head> <script type="text/javascript"> var xmlHttp function GetXmlHttpObject() { var objXMLHttp=null if (window.XMLHttpRequest) { objXMLHttp=new XMLHttpRequest() } else if (window.ActiveXObject) { objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP") } return objXMLHttp } function testajax() { xmlHttp=GetXmlHttpObject() if (xmlHttp==null) { alert ("Browser does not support HTTP Request") return } var url="pulldata.php" xmlHttp.onreadystatechange=stateChanged xmlHttp.open("GET",url,true) xmlHttp.send(null) } function stateChanged() { if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") document.getElementById("show").innerHTML=xmlHttp.responseText if (xmlHttp.readyState==1 || xmlHttp.readyState=="loading") document.getElementById("show").innerHTML="<div align=center>Loading...</div>" } </script> <body> <form action="#"> <input type="button" value="View the newest member" onclick="testajax();" /> </form> <div id="show"></div> </body></html> Code (markup): pulldata.php <?php //select from database the latest records //save the data into the result[] //output the respective results echo'The latest member is: '.$results["name"].' '; ?> PHP: You have just knew how to code an AJAX application Other Important Information 1. My example uses responseText to display the server's output. Alternatively, you can use XML (responseXML) as output and have your client parse the results and display appropriately. 2. My example did not send any parameters to the server. This can be easily done by appending the URL before sending the request to the server and have the processing script grabbing the parameters via GET. You can also use POST to send your parameters to the server. Refer to the following resources for more info. An Even Quicker Example If you want to work with the above example without any database, simply echo some static messages and it will work accordingly. In addition, you will most probably cannot see the 'Loading..' message because of the virtually no load. You can overcome this by placing sleep(3); before echoing so that the system will pause 3 seconds and shows the 'Loading..' message. Other Useful Resources The following are some of the top sites that contains very useful information about AJAX: 1. http://ajaxpatterns.org/Main_Page - The main source of AJAX knowledge! 2. http://ajaxian.com/ -Useful information for reference. 3. http://ajaxblog.com/ -Another great site for AJAX examples. 4. http://www.ajaxload.info/ -Contains tons of useful loading images for free use. Hope that this guide will help you to enjoy learning AJAX
Good article. Check out DWR (Direct Web Remoting) -- getahead.ltd.uk/dwr/ It makes it easier to code AJAX.
Hi, I have used this example in some of my code and all was going well till I realised that I wanted all browsers to refresh with posted information. I did this by intervalHandle = setInterval("refreshPage()", 10000); I then defined refreshPage() to run the server side script and send back the latest set of data. This works fine in FireFox so when one browser posts something, within 10 seconds it is updated on all browsers. The problem I am having is with IE7, it just doesn't update the browser and behaves rather weirdly. If anyone with some AJAX knowledge could suggest what I am doing worng I would be eternally great full. Thanks