I have this html and ajax file, but it is not updating every second like I want it to. I want it to every second call getTime(). It only does it once, then nothing.
Any thoughts? Thanks.
<head>
<title>Auction</title>
<script type="text/javascript">
function getTime() {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","functions.php?action=getCurrentTime&id=13",true);
xmlhttp.send();
setTimeout(getTime, 1000);
}
window.setInterval(getTime, 1000);
</script>
</head>
<body>
<?php beginGetAllInfo(); ?>
</body>
Based on your sample code, the first thing that happens inside getTime()
is it checks if a variable named str
is empty, if so, it returns from the function. str
isn't defined (in your sample code), so it should return. Try removing that if
-statement, or initialize str
to something that won't cause the statement to fail.
Additionally, you have two statements that will (eventually) cause your code to execute twice per second: setTimeout(getTime, 1000);
and window.setInterval(getTime, 1000);
The first, setTimeout()
will execute the code one-time, after 1-second has elapsed. However, this is executed everytime the getTime()
method executes - so in theory it should run every second. The second, setInterval()
will execute the code on an interval of 1-second. So, your code will always execute every 1 second.
I'd recommend either removing the setTimeout()
line inside of getTime()
, or changing the setInterval()
to a setTimeout()
(to get the ball rolling, so to speak).