Cache busting AJAX requests and redirects

AJAX get and head requests are cached by default. This can cause problems when AJAX requests use the same URLs as a user would use during normal site navigation. jQuery can disable caching on a global or per-request basis. When doing so, jQuery adds a _={timestamp} parameter to the query string which should make each request unique. However, there are cases where an AJAX request results in a redirect which jQuery will happily follow. When that happens the _={timestamp} isn’t automatically appended to the new request, so the final response can still end up being cached by the browser even when you’ve told jQuery not to cache it. You can get around this in 2 ways:

  1. Make sure all redirects persist the _={timestamp} parameter, if present
  2. Add the proper header response parameters to prevent the browser from caching the request.

Here’s an easy way to implement the 2nd solution in Rails:

[gist id=a879915f7921a3ca11c3 file=application_controller.rb]

Cooking is like love. It should be entered into with abandon or not at all.

— Harriet Van Horne, Vogue Magazine, 1956