This article helps you get started with AJAX. You are expected to know some web related technologies and terms such as
We have 2 pages - index.jsp & details.jsp
index.jsp: This one just lists certain terms on the page and the user can click on a link (there's a link for each term) to fetch the definition of that term.
definition.jsp: This one fetches the definition for different words from a database. This page takes in the word id as a URL parameter and does the necessary lookups to get the definition of the word. I shall not go into the source code for this page. Just consider it to be a simple server side page that returns dynamic content based on URL parameters. (This page can be a simple static HTML page as well. But it makes it easier to see the benefits of a AJAX (and I mean callbacks to the server to get more information) when the content is something that is not static and cannot be loaded with the index.jsp itself.
The var http = createRequestObject() uses the createRequestObject() function to create the XMLHttpRequest object (depending on whether the user is using Internet Explorer or some other browser). This object is used to make all the AJAX requests to other pages on the server.
The second function makeGetRequest() is used to make the actual request to the server. The first line invokes the open() method on the XMLHttpRequest object. This method lets you specify the page to call on the server and also lets you specify that you want to use GET for the request. You can append parameters to the URL (the normal GET style) if you want to pass in some values to the page you are going to call. The other thing worth noting is that 'processResponse' is the name of the function that must be called when the response is received from the server. You can name this anything you want, but use the same name for the third function as well.
The third function processResponse() basically checks whether the response from the server has been received (the response is basically the text of the page returned) and assigns that text to a local variable called 'response'. After that the text within the <div> tag on the page (this text can be accessed using the property called innerHTML) is replaced with the text that was received as a response.
There are lots of things that could be changed here (and should be in production code).
I hope this article has helped you get started with AJAX. To get more information, visit the Mozilla site (http://developer.mozilla.org/en/docs/AJAX) for excellent articles on AJAX
Back To List of Tutorials
Written by Kiran Pai
Please send your feedback or comments to feedback [at] codecoffee [dot] com