HTML Dog
Skip to navigation

AJAX

In the early years of the web things were simple — a page was text, perhaps with styling, and it contained links to other pages. To get new content you moved from one page to the next. But as developers got more ambitious with the web, attempting to build interactive (“native-like” applications), it was obvious that there needed to be a way to load new content into a page without a full reload.

To retrieve new content for a page, like new articles on an infinite-scroll site or to notify you of new emails, a tool called an XML HTTP Request (XHR) is used. Web apps that do this are also called AJAX apps, AJAX standing for Asynchronous JavaScript and XML.

Almost all sites that pull in new content without a page reload (like Facebook, Gmail, Google Maps etc) use this same technique. In fact, it was Microsoft developing Outlook Web Access who originally created the XMLHttpRequest.

XML HTTP Request

So what does an XMLHttpRequest look like?


var req = new XMLHttpRequest();
req.onload = function (event) { . . . };
req.open('get', 'some-file.txt', true);
req.send();

The first thing to do is create a new XMLHttpRequest request, using the new keyword, and calling XMLHttpRequest like a function.

Then we specify a callback function, to be called when the data is loaded. It is passed information about the event as its first argument.

Then we specify how to get the data we want, using req.open. The first argument is the HTTP method (GET, POST, PUT etc). Next is the URL to fetch from - this is similar to the href attribute of a link.

The third is a boolean specifying whether the request is asynchronous - here we have it true, so the XMLHttpRequest is fired off and then code execution continues until a response from the server causes the onload callback to be fired.

The asynchronous parameter defaults to false - if it’s false, execution of the code will pause at this line until the data is retrieved and the request is called synchronous. Synchronous XMLHttpRequests are not used often as a request to a server can, potentially, take an eternity. Which is a long time for the browser to be doing nothing.

On the last line we tell the browser to fire off the request for data.

AJAX and Libraries

The AJAX technique has been developed to the point now where single-page apps are possible - one main request loads JavaScript code which then loads, asynchronously, other content from the server. Whole libraries and frameworks have been built to help do so, and we’ll take a look at them later.