1. Technology
Send to a Friend via Email

Introduction to Ajax

14. Caching of Requests

clr gif

If we have the one page performing multiple requests (either by aborting any outstanding request or by creating multiple request objects) and those requests are using the GET method and don't need to send any gata to the server then we have a slight problem with some browsers.

Browsers try to reduce the amount of data that needs to be retrieved from the server by caching what has already been retrieved on your computer. A subsequent request for the same data will grab the cached copy rather than going back to the server to get it.

Unfortunately some browsers will do this with your Ajax request even though the information on the server may have changed in the meantime any the page doesn't end up getting refreshed for subsequent requests. (The same thing can happen with full web pages having changed but that isn't as noticable to most people unless they are the one editing their own pages and wondering why their browser still shows the old version).

There are two ways that we can fix this - one in the Javascript and on in the server side code.

The Javascript solution is to update the URL being passed so that we pass a different value each and every time. We do this by adding a dummy variable to the end of the URL in the query string and assign it a different value each time that a request is made. The easiest way to do this is by adding the microsecond value of the current time which will be different unless your visitor manages to make two requests in the same microsecond.

url = url+'?dummy='+ new Date().getTime();

Doing this means that the URL is different for each request and so the cached copy doesn't get used. As the server side processing doesn't need the dummy field it just ignores it and processes exactly the same as if it weren't there.

The better solution though is to update the server side processing itself. What you need to do is to add a header into the response that instructs the browser not to cache the information in the first place. How you do this depends on the server side language you are using. The PHP version of the extra line you need is:

header('Cache-Control: no-cache');

©2014 About.com. All rights reserved.