Pages

Friday, 6 April 2012

Preventing Caching in AJAX URLs

If we have the one page performing multiple requests and those requests are using the GET method 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.

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

Solution 1:

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.

Solution 2:

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'); 

Going deep, put the following response headers in the page (using the PHP header() function):

<?php
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
?>

No comments:

Post a Comment