Sunday, April 8, 2012

Prevent caching of AJAX call



It looks like that if I load dynamic content using $.get(), the result is cached in browser. Adding some random string in QueryString seem 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() ?



Source: Tips4all

8 comments:

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

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

    $(document).ready(function() {
    $.ajaxSetup({ cache: false });
    });

    ReplyDelete
  3. 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).

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

    ReplyDelete
  4. A small addition to the excellent answers given: If you're running with a non-ajax backup solution for users without javascript, you will have to get those server-side headers correct anyway. This is not impossible, although I understand those that give it up ;)

    I'm sure there's another question on SO that will give you the full set of headers that are appropriate. I am not entirely conviced miceus reply covers all the bases 100%.

    ReplyDelete
  5. What about using a POST request instead of a GET...?
    (Which you should anyway...)

    ReplyDelete
  6. Maybe you should look at $.ajax() instead (if you are using jQuery, which it looks like).
    Take a look at: http://docs.jquery.com/Ajax/jQuery.ajax#options and the option "cache".

    Another approach would be to look at how you cache things on the server side.

    ReplyDelete
  7. Of course "cache-breaking" techniques will get the job done, but this would not happen in the first place if the server indicated to the client that the response should not be cached. In some cases it is beneficial to cache responses, some times not. Let the server decide the correct lifetime of the data. You may want to change it later. Much easier to do from the server than from many different places in your UI code.

    Of course this doesn't help if you have no control over the server.

    ReplyDelete
  8. You can use the short notation $.now() instead of doing a (new Date().getTime()) each and everytime.

    ReplyDelete