Preventing Ajax Request Caching in MooTools – introducing Request.NoCache
Ajax requests are, generally speaking, used to update the document or meant to send and fetch new data to and from the server. In Ajax heavy apps, you might end up sending the same request on numerous occasions and not always expect the server to respond with the same results.
This can cause problems with caching. Internet Explorer in particular will see an ajax request with the same parameters and just return the results it got last time, which, well, sucks.
I have this trick that I’ve been using for a while now and I figured I’d release it. The solution is to include a value in your request that’s always different. My solution has been to add a “noCache” value set to the current time. So long as I’m not sending the same request more than once in a millisecond, this solves my problems.
Hot on the heals of yesterday’s plugin (Class.refactor), I’m releasing this tweak on the Request classes that introduces the ‘noCache’ option that will automate this for you. Simply set the ‘noCache’ option to true and you’re all set.
new Request({
url: '/foo.php',
data: {...some data...},
noCache: true
}).send()
Don’t want to set it every time? No problem, just switch the default for the option to true with Class.refactor:
(function(){ //let's not pollute the global namespace
var setNoCache = function(cls) {
return Class.refactor(cls, options: {
noCache: true
});
};
Request = setNoCache(Request);
Request.HTML = setNoCache(Request.HTML);
})();
//all future instances of Request and Request.HTML
//default to using the noCache functionalty
Man. I’m on a roll this week. You can download this script on the download page and view the docs.
Follow @clientcide on twitter to get notified of new posts.
To follow me personally on twitter, follow @anutron.
November 20th, 2008 at 4:50 pm
You ARE on a roll this week….
Thanks, very pratical solution. I didn’t know about this, is the caching of the request IE-only or does it also appear with gecko/webkit?
November 21st, 2008 at 2:27 am
You know, to be frank, I can’t remember. I’ve had this little fix in my toolbox for so long that I honestly can’t recall which browsers suffer from it. I only thought of releasing it today because someone asked me how I deal with the problem, and they were specifically struggling with IE.
November 21st, 2008 at 1:25 pm
I can verify this being an issue with primarily IE, I have solved in the past using the random number function of JavaScript. My original technique also use the current time but there was a slight chance that the request could be made in the exact same time, so I use a random number between 1 and 99999. The chances of it be exactly the same are almost nil.
Having the no cache option within the request call will surely save me time, thanks for the addition.