Prevent browser caching of AJAX call result
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) {
console.log(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.
What is the correct way to prevent caching on ajax calls?
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()
Prevent browser from caching AJAX requests
The browser cache behaves differently on different settings. You should not depend on user settings or the user's browser. It's possible to make the browser ignore headers also.
There are two ways to prevent caching.
--> Change AJAX request to POST. Browsers don't cache POST requests.
--> Better Way & good way: add an additional parameter to your request with either the current time stamp or any other unique number.
params = "action=" + action
+ "&domain=" + encodeURIComponent(domain)
+ "&preventCache="+new Date();
How to prevent a jQuery Ajax request from caching in Internet Explorer?
You can disable caching globally using $.ajaxSetup()
, for example:
$.ajaxSetup({ cache: false });
This appends a timestamp to the querystring when making the request. To turn cache off for a particular $.ajax()
call, set cache: false
on it locally, like this:
$.ajax({
cache: false,
//other options...
});
Disable AJAX Caching
You can send random parameters using POST, while sending the important vars using GET if you need to.
If you have problems with IE, I know that sending something with POST makes it to stop caching server responses
Prevent caching of the ajax response
You can append a random number to your file:
xmlhttp.open("GET","note.xml?" + Math.random(),false);
This will ensure that the browser always gets the latest version because it will never cache find a cached version that matches the random.
How to prevent Ajax/javascript result caching in browsers?
Add a random query string to the URL you are sending.
E.g. if the Ajax request is sent to "http://www.xyz.com/a"
then add a random string at the end: "http://www.xyz.com/a?q=39058459ieutm39"
Prevent browser caching of MVC partial pages as full pages (on back/forward)
Turns out the trick is to turn off caching on the Ajax request that pulls the partial pages, not on the server as that is never hit (the light suddenly came on after writing the above question):
$.ajax(
{
cache: false, // << Added this
url: url,
type: "GET",
error: function (jqXHR, textStatus: string, errorThrown: string)
{
// On error (eg. "not found") empty out the display
THIS._removeContent();
},
success: function (data: string, textStatus: string, jqXHR)
{
var $data = $(data);
THIS._insertContent($data, function ()
{
});
}
});
The cache false also apparently ensures the browser will not reuse the page on page back/forward operations.
Related Topics
I'Ve Heard Global Variables Are Bad, What Alternative Solution Should I Use
How to Read and Write into File Using JavaScript
Whats the Best Way to Update an Object in an Array in Reactjs
How to Find Object in Array by Property in JavaScript
Converting an Object to a String
What's the Right Way to Decode a String That Has Special HTML Entities in It
How to Post a File from a Form With Axios
How to Provide Named Parameters in a Function Call in JavaScript
Null-Safe Property Access (And Conditional Assignment) in Es6/2015
How to Set File Input Value When Dropping File on Page
Is "Clear" a Reserved Word in JavaScript
How to Detect My Browser Version and Operating System Using JavaScript
Mocha/Chai Expect.To.Throw Not Catching Thrown Errors
How to Group Data with an Angular Filter
Handle Response - Syntaxerror: Unexpected End of Input When Using Mode: 'No-Cors'