Preventing Cache Issues in AJAX calls
Tyler, who visited my blog recently, mentioned that he’s having issues with caching of the files when he uses AJAX. Basically, the result called in from the AJAX code from the php (or could be ASP or any other server-side scripting file, or even an HTML file) would often be a repeat of the last call, resulting in a wrong output. He figured it was an IE cache issue and was attempting to fix it that way.
” . . . the server side file does NOT ever have direct contact or exposure to the client side – only the AJAX code does. Hence, AJAX caching is a server-side issue, not a client-side issue.”
In most AJAX calls, the variables are sent this way : serversidefile.php?name=Jeff&phone=604xxxxxxx&gender=male
In this case, because the variables would most likely be different each time between users, the server wouldn’t use the cache at all. serversidefile.php?name=Jeff&…. is different from serversidefile.php?name=tyler&… from the server’s perspective, so it will make the call each time.
However, sometimes you get situations where the same call string could be repeated. In this case, you enter a random number field to the query.
serversidefile.php?rand=[random]&name=Jeff&….
Here’s how to generate random numbers in javascript :
var randomnumber=Math.floor(Math.random()*1000)
I picked 1000 as a safe zone, but if you want more certainty you can increase the range to 1000000. After the random number has been generated, simply toss it into the url of the AJAX call :
url = ‘filename.php?rand=’+randomnumber+’&name=’+name+’&…..’
That will prevent caching of the server-side files by your AJAX calls.




(4.67 out of 5)
No comments yet.