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.”

However, you must remember that AJAX calls go to the server. The Javascript file is run on the client-side, and it hits the server with either a GET or a POST type call. When it does that, the server-side file responds in a certain way, and then ONLY the result string is sent back via headers. In this process, 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. The server does caching of the files sometimes (I don’t know a lot about the behaviour, how often it does it etc. but I know how to prevent it).

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.

By |2007-03-11T13:54:49+00:00March 11th, 2007|Categories: Coding, Online Security, Web Development|2 Comments

About the Author:

CEO Of Brixwork Real Estate Marketing Inc.