I have an AJAX-call, which returns values from a ever changing database, based on simple standard parameters, like month of year. In IE, this function returns cached data, which it never should. I've monitored the server side, and it isn't contacted by the client.
Now, my title question has been asked in different ways, many times here already. The top two solutions are:
cache: false
The thing is though, that cache: false
doesn't work, at least not in my application. On the other hand, passing a unique string to prevent caching, seems like a quick fix hack. I don't like it. So what is the correct way of preventing caching on ajax calls?
Ajax call that doesn't work in regards of preventing caching:
$.getJSON("myURL", {
json : jsonDataObject,
cache: false
}).success(function(data) {
//do something with data
});
I have also tried calling $.ajaxSetup({ cache: false });
on it's own, before the calls happen, but to no effect...
First of all, the way you think you're setting cache
to false in your $.getJSON()
call is incorrect. You're passing a key/value pair to the server so the request URL will look like site.com/resource?cache=false
.
You need to make your request using the $.ajax()
method so you can actually set the cache
option to false
. However, all this does is what you call a "quick fix hack". It adds _={current_timestamp}
to the query string so that the request will not be cached.
$.ajax({
url: 'myurl',
type: 'GET',
dataType: 'json',
data: jsonDataObject,
cache: false, // Appends _={timestamp} to the request query string
success: function(data) {
// data is a json object.
}
});
In my opinion that's not a quick fix or a hack, it's the correct way to ensure you get a fresh response from the server.
If you'd rather not do that every time, then you can just use your own wrapper function:
$.getJSONUncached = function (url, data, successCallback) {
return $.ajax({
url: url,
type: 'GET',
dataType: 'json',
data: data,
cache: false, // Appends _={timestamp} to the request query string
success: successCallback
});
};
Then you can just replace your call to $.getJSON()
with $.getJSONUncached()
Please let us know are you using IE8 as for that please check the below from jquery documentations
cache (default: true, false for dataType 'script' and 'jsonp') Type: Boolean If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With