PHP and AJAX Caching Bug
Wow, this one “bugged” me for days.
I have a PHP form that gets data from Oracle. When I click the submit button, I want another page to process some script to keep a many-to-many table up to data.
For example:
<input type=submit onClick=submitDistricts($PUBID)>
The Javascript calls a GET
function submitDistricts(PUBID)
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleDistrictResponse(xmlHttp.responseText);
}
}
xmlHttp.open(“GET”, “updateDistricts.php?PUBID=”+PUBID);
xmlHttp.send(null);
}
And this works pretty well. Except that the call gets cached and I can only submit it once. YIKES!!
How did I fix it? Well ensure the GET is always unique.
Change the line from:
xmlHttp.open(“GET”, “updateDistricts.php?PUBID=”+PUBID);
TO:
xmlHttp.open(“GET”, “updateDistricts.php?PUBID=”+PUBID + ‘&’ + Math.random());
That’s it. Now my AJAX call to the database is always unique and has no caching…
That was a weird one!
March 12, 2009 at 11:08 pm
Hi Gordon,
LTNH
Yeah, that’s a really tough one to track down; that’s bitten me too. The one problem is, the random number solutions (which just makes the browser’s cache think it’s a different document) will start cluttering up the cache with redundant copies of the same/similar data. Of course, that’s better than something not working at all, but it’s a side effect you might need to keep track of.
More at http://en.wikipedia.org/wiki/XMLHttpRequest#Caching which also suggests putting a meta tag into the HTML (when applicable) to force the contents to expire. Of course, if it’s not HTML, that’s not an option.
March 13, 2009 at 1:13 pm
Thanks Tomas,
I went to that site and noticed the meta-tag workaround for caching, but I haven’t tried it yet: