Prevent browser caching of jQuery AJAX call result

Prevent browser caching of jQuery AJAX call result

It looks like if I load dynamic content using $.get(), the result is cached in browser.
Adding some random string in QueryString seems to solve this issue (I use new Date().toString()), but this feels like a hack.
Is there any other way to achieve this?
Or, if unique string is the only way to achieve this, any suggestions other than new Date()?


Solution 1:

I use new Date().getTime(), which will avoid collisions unless you have multiple requests happening within the same millisecond:

$.get('/getdata?_=' + new Date().getTime(), function(data) {

Edit: This answer is several years old. It still works (hence I haven’t deleted it), but there are better/cleaner ways of achieving this now. My preference is for this method, but this answer is also useful if you want to disable caching for every request during the lifetime of a page.

Solution 2:

The following will prevent all future AJAX requests from being cached, regardless of which jQuery method you use ($.get, $.ajax, etc.)

$.ajaxSetup({ cache: false });

Solution 3:

JQuery’s $.get() will cache the results. Instead of

$.get("myurl", myCallback)

you should use $.ajax, which will allow you to turn caching off:

Related:  How to get value at a specific index of array In JavaScript?
$.ajax({url: "myurl", success: myCallback, cache: false});

Solution 4:

another way is to provide no cache headers from serverside in the code that generates the response to ajax call:

response.setHeader( "Pragma", "no-cache" );
response.setHeader( "Cache-Control", "no-cache" );
response.setDateHeader( "Expires", 0 );

Solution 5:

All the answers here leave a footprint on the requested URL which will show up in the access logs of server.

I needed a header based solution with no side effect and I found it can be achieved by setting up the headers mentioned in How to control web page caching, across all browsers?.

The result, working for Chrome at least, would be:

   url: url, 
   headers: {
     'Cache-Control': 'no-cache, no-store, must-revalidate', 
     'Pragma': 'no-cache', 
     'Expires': '0'

Solution 6:

Personally I feel that the query string method is more reliable than trying to set headers on the server – there’s no guarantee that a proxy or browser won’t just cache it anyway (some browsers are worse than others – naming no names).

Related:  javascript object variable key [duplicate]

I usually use Math.random() but I don’t see anything wrong with using the date (you shouldn’t be doing AJAX requests fast enough to get the same value twice).