Just To Add My Voice To The Random Query Trick

Once again I came face to face with a problem that seemed insurmountable. That little piece of nuisance that just seems to make your code not what you expect it to be. To put it simply, all I needed to do was to prevent an image I kept reloading dynamically from the server from being cached. A common problem faced by any new AJAX developer, and once again after Googling my ass off, I came across the solution to prevent caching on the client side.

The solution: “Append a random query string to whatever you are requesting from the server to prevent it from being cached”.

To prevent an image from being cached (which was my case), you could try something like this (PHP CODE Below):

// return image to be displayed

echo ‘<img  src=”‘ . $_POST[‘Picture’] . ‘?’ . rand(1,100) . ‘” width=”150″>’;

The echoed image information should have a randomly generated number between 1 and 100 appended to the query for the image, so a fresh image is returned always from the server. This works great in whatever situation you need to bypass the cached information on the client, be it Javascript, CSS or Images.