Preserve Context In Your Ajax Calls

Asynchronous Ajax calls can really mess you up. The problem is that the environment within which you execute an Ajax call isn’t the same environment as when you handle the results. This situation occurs because of the nature of asynchronous environments. The browser makes the Ajax call to the server and then continues with its own business. Sometime later, the server responds with the results of the Ajax call, but by that time, the context of the browser’s running thread has changed.

It’s like arriving at the train station after the train has left town.

The key to solving this problem is to save the context when making the Ajax call, so that it gets restored when handling the results of the call. In jQuery, the object attribute that can preserve your context is named, oddly enough, “context.”

In the code sample below, we wish to place an image into a DIV element, but only if the image actually exists on the server. If the image doesn’t exist, we put in some generic text. In this specific case, we’ll display the image of a book, if it’s available. If not, we display the book title and its author in text. Note that the “book” object has members for imageFile, title and author. Also note that all this code appears within the context of the DIV element, as referenced by $(this).

  url: '/images/'+book.imageFile,
  type: 'HEAD',
  context: $(this), // This is where $(this) gets preserved!
  error: function() {},
  success: function () {
    // $(this) is the $(this) that was preserved in the context
    $(this).html('<img src="/images/'+book.imageFile+'">';

var outHtml = '<p style="text-align:center;font-style:italic;">'+book.title+'</p>';
outHtml += '<p style="text-align:center;">by</p>';
outHtml += '<p style="text-align:center;">''</p>';

Note that the book title and author get displayed right away. As soon as the image becomes available, it will replace the title and author text. So you might briefly see the title and author flash on your screen until the actual image is loaded. If the image is not available, it simply does not load, and the program issues no complaints.