I'm writing a web page that uses AJAX to poll the server every few seconds to see if there are any updates to data. Works great in IE6 and older using the XMLHttpRequest ActiveX object that you can instantiate from the progid "Msxml2.XMLHTTP.6.0". In order to keep polling I've got an event handler listening to the onreadystatechange event that calls a setTimeout at the end, so it pauses for 5 seconds, then calls into another function that sends out another request. Once you get the ball rolling, it keeps going. Here's the code:
var xhr = new ActiveXObject("Msxml2.XMLHTTP.6.0");
xhr.onreadystatechange =
function() { if (xhr.readyState == 4) { if (xhr.status == 200) { doUpdates(xhr.responseText); // Go do the updates from the response text
setTimeout(
"checkUpdates();",5000); // Poll again after 5 seconds } }
};
function
checkUpdates(){ // See if there has been a change in the data visible to this user xhr.open(
"POST","poll.ashx", true); xhr.send(username
);}
// This kicks it all off:
setTimeout("checkUpdates();",5000); // Kick off the first poll after 5 seconds
I really should make a watchdog that runs every 20 seconds in case something gets hung up, but overall the every 5 second polling thing works quite well. Except in IE7.
UPDATE: I was fooled, and later found out that the problem actually lies in the reusability of the XMLHttpRequest object in IE7. Like in FireFox, you can't use it for more than one request, and have to new up another each time you call back to the server. But the older ActiveX versions of XMLHttpRequest can be reused.
If you try to use this polling technique with the native XMLHttpRequest object in IE7, then when it is in the event handler code apparently it runs in a different security context or something, and after the setTimeout object is brought to life, it disappears as soon as execution leaves the event handler! Must be some kind of attempt to provide enhanced security for AJAX, but unfortunately this makes it ridiculously difficult to create a routine that polls on a consistent basis, a few seconds after a response is returned. I ended up just using the old-school Msxml2.XMLHTTP.6.0, which fortunately is still supported in IE7.