Getting started with Ajax - build your own smallest ajax framework
Ajax (Asynchronous JavaScript and XML) have drastically changed the way Web application work. Effective and controlled use of Ajax can make Web applications highly responsive. In this article, I will take you through the fundamentals of Ajax. We also build a small ajax library JavaScript file which can be used as the starting point for your projects.
Note that there are a lot of Ajax frameworks available such as DOJO and YUI. But one issue with these frameworks is that they are somewhat big. If your application has to work with a lot of dialup users, you will have optimize these frameworks. Also you will have to make use of tools such as YUI compressor.
So if you are just looking for simple Ajax functionalities such as refreshing a portion of a Web page, it is better to go with your own small Ajax framework.
Ajax as the term suggests enables us to retrieve content asynchronously over HTTP request. Along with DHTML you can use this to update selected sections of a Web page.
In order to use Ajax, you need to first get a JavaScript browser object called XMLHttpRequest. Using this you can make asynchronous HTTP requests. But the implementation of this object is unfortunately browser dependent! So our first task is to write a JavaScript function which returns XMLHttpRequest in a browser independent way. Let us call this function getXMLHttpRequest(),
function getXMLHttpRequest() { if (window.XMLHttpRequest) { return new XMLHttpRequest(); } else if (window.ActiveXObject) { try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} } } return null; }
Now let us write a function which will use the XMLHttpRequest to do an HTTP GET request,
function getAjaxContent(url, callback) { var ajax_req = getXMLHttpRequest(); ajax_req.onreadystatechange = callback; ajax_req.open('GET',url,true); ajax_req.send(null); }
But where do we get the content of our Ajax request? The second argument to the getAjaxContent is a function pointer and this function will be invoked during Ajax execution. Remember - Ajax execution is asynchronous!
Now in our application we can use the above two methods for Ajax calls. Here is a sample which retrieves an RFC document using Ajax,
function getRFC22() { getAjaxContent("http://www.ietf.org/rfc/rfc0022.txt",cb); } function cb() { if(this.readyState==4) { alert(this.responseText); } }
If the URL you are accessing returns HTML, you will need to use this.responseXML instead of this.responseText
Related Articles
Leave a Comment
Got any comments/queries about this article? You can post them above and I will get back to you. You can also subscribe to the RSS feed to get latest updates on this site. Got a good coding tip? Send it to me with your name and I will publish it here.