David Reynolds

Welcome to boredom

Javascript Ajax Caching Issues in Internet Explorer 6

| Comments

I’m sure this is an old, long talked about issue but I’m mainly recording it here for my own memory.

I had an issue with IE6 whereby an AJAX request would only work sometimes, I couldn’t see a pattern to it but it only did it in IE6 and worked in IE7/Firefox/Safari. After some Googling (and swearing) I came across this blog post from Christopher Craig which seemed to have the answer.

Christopher mentions that IE caches everything it sees and that if you try and make an AJAX request to the same URL (which I was doing) then IE will use it’s cached version, whether you like it or not. The workaround Christopher suggests it to append the time to the url so that IE sees it as a different URL.

I’ve altered this slightly to use a random number, like so:

1
2
3
4
5
6
7
8
function setOpenMenu(element) {
  myRand = parseInt(Math.random()*999999999999999);
  http_request = new getXMLHttpRequest();
  http_request.open('GET', '/session/?open=' + element + '&parent=' + \
             $(element).parentNode.id + '&dontcacheme='+ myRand, true);
  http_request.onreadystatechange=alertContents;
  http_request.send(null);
}

and as if by magic… it works!

Comments