Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable Ajax caching?

I am having an issue with ajax caching, This was a problem in IE browser too but i fixed it by Writing the Following code.

    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("expires","-1");
    response.setHeader("pragma","no-cache");

But I see Safari4.0 on MAC is Caching the Ajax request(We have a requirment to support this). Fire Fox never a problem. Regarding this "Expire" i am setting it to -1, i see lot of places it is set 0 or some old date from past. Will it make a difference?

like image 982
pushya Avatar asked Mar 30 '12 18:03

pushya


People also ask

Do Ajax calls get cached?

Although we can use a standard caching solution provided by HTTP (yes, Ajax is cached by HTTP), there is a catch: It works for GET requests only (not POST).

What is cache in Ajax?

The cache: false is used by developers to prevent all future AJAX requests from being cached, regardless of which jQuery method they use. We can use $. ajaxSetup({cache:false}); to apply the technique for all AJAX functions. BY Best Interview Question ON 26 Feb 2019.

What is ajaxSetup?

The ajaxSetup() method in jQuery is used to set the default values for future AJAX requests. Syntax: $.ajaxSetup( {name:value, name:value, ... } )

How do you cache Javascript?

You can cache a resource using three methods add , addAll , set . add() and addAll() method automatically fetches a resource, and caches it, whereas in set method we will fetch a data and set the cache. });});


2 Answers

Send an extra parameter with your GET request that will never be the same, for example, the current timestamp. Something like:

url = url + '&nocache=' + new Date().getTime();

This will prevent caching.

like image 132
Ry- Avatar answered Sep 19 '22 17:09

Ry-


First, a note on your Expires header. Your question doesn't specify what server framework you're using, so I'm not sure if this is applicable. However, it looks like you might be sending an invalid Expires header.

The RFC requires Expires to be a date, however you appear to be setting the header to a literal "-1". There are many frameworks that have an expires property on their HTTP response object that takes an int and automatically calculates a date that is that number of seconds from now.

Use a HTTP inspector to ensure that your server is sending a validly formatted date and not -1 in the Expires header.


You might try making your Cache-Control header more restrictive:

response.setHeader("Cache-Control", "private, no-cache, no-store, must-revalidate");

must-revalidate tells caches that they must obey any freshness information you give them. HTTP allows caches to serve stale representations under special conditions; by specifying this header, you’re telling the cache that you want it to strictly follow your rules. [1]

like image 22
josh3736 Avatar answered Sep 21 '22 17:09

josh3736