General Thoughts

Quick Solution to Ajax Caching Issue

By Thinkman  ยท  July 23, 2008

Share: LinkedIn ๐• / Twitter

I came across this quick fix for an Ajax caching issue and thought it worth sharing. The original post was by Eric Pascarello on JavaRanch Radio โ€” the site is long gone but the solution is as relevant today as it was then. An archived copy of the original can be found via the Wayback Machine.

The Problem

Your Ajax request is grabbing a cached page from the previous request instead of fetching fresh data from the server. You make a call, get a response โ€” but it is the same stale response you got last time.

The Fix

Append a random query string value to your request URL. That is it.

// Append a timestamp or random number to bust the cache
var url = "/api/data?nocache=" + new Date().getTime();

// Or with an existing query string
var url = "/api/data?id=123&nocache=" + Math.random();

Why It Works

When a browser looks at a request URL, if it finds a match in its cache it uses the stored data rather than making a new network call โ€” great for static assets, terrible when you need fresh dynamic data.

By appending a random or timestamp-based value to the URL parameters, every request looks like a brand new URL to the browser. It cannot find a cache match, so it has no choice but to go and fetch the data fresh from the server every time.

In the words of the original post โ€” the browser is forced to say: "Stop the press! We have new info here. Let us go get the data!"

A Note on Modern Alternatives

This trick still works perfectly in 2008 and beyond. For more control, modern browsers also respect the Cache-Control: no-cache response header set server-side, or the cache option in jQuery Ajax (cache: false) which does exactly this automatically.

# General Thoughts
← Older post
A Trip to Srirangapatna and Mysore
← Back to all posts