Introduction


Figure 1 In the past web pages were limited in the sense they had to load in their entirety. Changing even a small portion of the content required a new web page to be loaded.

Thankfully modern web sites don't suffer from this restriction because AJAX allows us to communicate with server-side scripts behind the scenes via a JavaScript XMLHttpRequest object after a web page has loaded.

When you vote on an ITNewb article AJAX is used to send the request to one of our servers which updates the database and responds with a simple XML document that contains updated statistics. The response is then used to update a few areas on the web page with the new voting statistics without the web page itself ever reloading.

An XMLHttpRequest object isn't limited to the HTTP protocol as its name implies but also supports other connection types such as FTP. You can send and receive information in XML, HTML or plain text via GET, POST, HEAD or any other method supported by your server. This really opens things up and allows us to take interactive web applications to the nth level.

Prerequisites


This article assumes you have a basic knowledge of HTML, CSS and JavaScript. If you don't you may find this article hard to follow, especially on the JavaScript front. In the event you're not quite ready for this article, here are a few links to help get you started.

Where it Started


The class needed to make HTTP requests with JavaScript was first introduced in Internet Explorer 5 as an ActiveX object called XMLHTTP. Mozilla (1.0 / Netscape 7) and Safari (1.2) followed suite by implementing the XMLHttpRequest class into their browsers which supported the properties of the original Microsoft ActiveX object.

For some time these nifty JavaScript classes were little known but their popularity grew as high profile sites like Google began using them.

How it works


When you think of AJAX you shouldn't think of JavaScript by itself. AJAX works through a combination of various technologies all coming together to produce powerful results. The AJAX equation involves incorporating the following technologies:
  • HTML / XHTML and CSS for presentation
  • Client-server communication via an XMLHttpRequest object
  • Crawling the DOM and modify DHTML via a client-side scripting language like JavaScript

JavaScript events are usually used to trigger AJAX, such as a user clicking a hyperlink or perhaps a timer expiring. Here is how the entire process works from start to finish.
  • An event occurs that calls a JavaScript function;
  • the JavaScript function creates or reuses a request object;
  • a callback function is assigned to handle the server response;
  • the request is formulated and sent via the request object;
  • the server processes the request and responds;
  • the callback function catches the response, parses it and updates the DHTML; and
  • finally the updated presentation is shown to the user.

Figure 2

Continue with XMLHttpRequest Class ➜