[code]
The time is <div id="time">unknown</div>
<body onLoad="init()">
<script type="text/javascript">
function updateTime()
{
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("time").innerHTML=xmlhttp.responseText;
}
else
{
}
}
xmlhttp.open("GET", "time.php?t=" + Math.random(), true);
xmlhttp.send();
setInterval("updateTime", 1000);
}
</script>
<button type="button" onclick="updateTime()">Change Content</button>
</body>
[/code]
I'm just going through the W3School tutorial for Ajax but wanted to see if I could make the time refresh every second so I added a SetInterval() but it doesn't appear to work, what am I doing wrong?
there is no init function
Yeah I got rid of that because it didn't seem to do anything either. Forgot to remove the onLoad.
Lose the quotes around updateTime
[editline]20th October 2010[/editline]
On the setInterval line, not onclick
[html]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Time</title>
<script type="text/javascript">
function update(){
setInterval(function(){
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("time").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", "time.php?t=" + Math.random(), true);
xmlhttp.send();
}, 1000);
}
</script>
</head>
<body>
<button type="button" onclick="update()">Start</button>
The time is <div id="time">unknown</div>
</body>
</html>
[/html]
Moved some things around. Just how I'd do it.
Sorry, you need to Log In to post a reply to this thread.