Just an idea for you how to solve this kind of problem cleaner.
Service-Side (REST-style JSON service):
getRandomNumber.php:
PHP Code:
<?php
header("Content-Type: text/x-json");
$i = rand(0,10);
print('{ "value" : "'.$i.'" }');
?>
Client-Side (XmlHttpRequest):
PeriodicUpdater.js:
Code:
(function() {
function createXmlHttpRequestObject()
{
var xmlhttp = false;
try
{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest != 'undefined')
{
try
{
xmlhttp = new XMLHttpRequest();
}
catch (e)
{
xmlhttp = false;
}
}
if (!xmlhttp && window.createRequest)
{
try
{
xmlhttp = window.createRequest();
}
catch (e)
{
xmlhttp = false;
}
}
return xmlhttp;
}
window.PeriodicUpdater = function(element, service, period);
{
if (typeof(element) == "string")
{
this._element = window.document.getElementById(element);
}
else
{
this._element = element;
}
this._service = service;
this._period = period;
this._request = createXmlHttpRequestObject();
this._active = false;
};
PeriodicUpdater.prototype = {
start: function()
{
if (!this._request) { return; }
if (this._active) { return; }
this._active = true;
window.setTimeout(this._update(), this._period);
},
stop: function()
{
this._active = false;
},
_update: function()
{
if (!this._active) { return; }
this._request.open("GET", this._service, true);
this._request.onReadyStateChange = function() {
if (this._request.readyState != 4) { return; }
var response = eval('(' + this._request.responseText + ')');
while (this._element.hasChildNodes())
{
this._element.removeChild(this._element.firstChild);
}
this._element.appendChild(window.document.createTextNode(response.value));
};
window.setTimeout(this._update(), this._period);
}
};
})();
Usage in html:
Code:
<div id="update"></div>
<script type="text/javascript">
var updater = new PeriodicUpdater("update", "http://example.com/getRandomNumber.php", 2000);
updater.start();
</script>
This code is untested (but the whole XmlHttpRequest boilerplate is copy&paste from a working script, so there should be no major problems with it)