2010/11/16

XMLHttpRequest not refreshing

I have been playing for some days now with writing some interacting javascript (dynamic forms and so on). Although I already did that in the past I had never played around with the XMLHttpRequest object. To overcome that I tried the XMLHttpRequest so that I could split up data from the javascript code.

One thing I noticed was that the xml request was cached by IE. I tried refreshing the page but this didn't help. The only thing I could do was surf manually to the xml and refresh it so that the cache was updated. This ofcourse was not acceptable. I found two solutions that worked for me.

The first solution was creating a hidden iframe that showed the xml. When you refresh the page, it also refreshes the iframe and thus the cache is updated. Not elegant but it works for not so dynamic pages. Here is an example

<div style="visibility:hidden;display:none"><iframe src="http://tendertechie.tries.technology.com/myxml.xml" id="resframe"></iframe></div>

*** btw if you want to post html code like this but don't want it to be interpreted on blogger.com, you can change the lesser then sign < by the html equivalent &lt; and ofcourse the > by &gt; . To show this code again I used &ampgt; :D


The second one I came up with was while I was driving my car. I was thinking about an old webbased game I used to play (http://cq2.speedxs.nl/indexnl.php). I remembered that while traveling, the webmaster added a ?move=c first in the url and then a ?move=q for the following request. The pattern was constantly alternating. This allowed the page to be refreshed without having caching problems. When I came home I tried to add ?upd=randomdata to my xml url and see if it would display the data correctly (this was the case). This led me to believe that I could refresh the data by adding random new data every time I requested an xml. And was is more "random" then time (read is always different). I came up with the following code

function getXMLDocViaMethod(url,method,reload)
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(reload)
{
var d = new Date();
url = url+"?updch="+d.getTime();
}
xmlhttp.open(method,url,false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
return xmlDoc;
}

If you want to read more about xmlhttprequest, I suggest using the w3schools site. They have good examples that you can interactively try out. Here is a quick link!

No comments:

Post a Comment