Tuesday, 29 October 2013

Coping with Browser Cache in AJAX calls

When using jQuery to perform AJAX calls the following is typical

$.get("myScript.php",{'arg1':val1,'arg2':val2},function(json){
  ...
},'json')

I have found that the browser can supply an old result from its cache when I want a new result to be evaluated.

The solution is to add another argument to the cgi pack which contains a value which is guaranteed to be 'new'. This will stop the browser using a cached result. The value of the argument is conveniently supplied by the Javascript Date package. Of course myScript.php can just ignore the extra argument.

$.get("myScript.php",{'arg1':val1,'arg2':val2,'antiCache':antiCache()},function(json){
  ...
},'json')

function antiCache(){
return (new Date()).getTime();
}

[The getTime() method returns the number of milliseconds between midnight of January 1, 1970 and the specified date.]