Introduction

Have you ever notice that many modern websites update their content without refreshing the page? Your Instagram/Facebook/Twitter feeds, email inbox and amazon shopping cart can all have their content dynamically rendered without the need for your browser to refresh the page.

This behaviour is powered by a technique called Asynchronous JavaScript and XML (AJAX), and allows a browser to send requests with refreshing the page. Lets have a look at a quick example.

Google Away!

Let’s visit everyone’s favourite site. We send a GET request and receive in our browser a new web page:

Google Home

This is a pattern you’re hopefully familiar with. The same GET request/response pattern underpins much of the internet. Anytime you visit a new page, follow a link, or go stalk your ex’s photos on Facebook, your browser follows this pattern.

But what if as a developer we want to update data on our page without refreshing it. This sort of dynamically served content is quite prevalent through out the internet. Google presents a great example. When we start typing in the search bar, the page changes dramatically and we get a list of suggested searches:

Google First Letter

This is achieved without reloading the page. The content just dynamically updates when you type in a letter, a clear sign that an AJAX request has been made. If we look at the console while typing in a letter we see a request gets generated:

Google Home

Looking at the type of the request we see the code xkh. This stands for XMLHttpRequest, which is the API used by AJAX requests. So we’ve got a new way to serve content. We can either use a normal http request to refresh the page, or an ajax request to serve the content without changing the page.

AJAX Server Flow

As you can see the key difference between the too is that in an AJAX request, the browser will keep running code. This is where the asynchronous-ness of it comes in. It sends off a request, but doesn’t wait for the response. Instead we specify when we make the request we specify a callback function which tells the browser what to do with the data it gets back. An example in JavaScript would look like this:

$.get("http://www.google.com/....", function(data) {
  $('#target_element')[0].innerHTML = data;
})

The callback function here takes the data we get backs and inserts it into the target element. With these kind of functions we can create a whole application on a single web page. The problem with doing this is we very quickly begin to break any kind of encapsulation, single responsibility or idea of good design. So it’s important we’re careful to only use AJAX requests in an sensible way.

Updated:

Leave a Comment