Domanda

I'm trying to modify this http://www.w3schools.com/php/php_ajax_database.asp

I'm just using the HTML part of that ^. My php file only have

<?php
echo rand();
?>

And it works fine! It updates every time I switch something on the drop-down list. But, I want it to run every second, but it won't work. This is what my HTML looks like:

<html>
<head>
<script>
function showUser() {
  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","ajax/test.php?q="+str,true);
  xmlhttp.send();
}
setInterval(showUser, 1000);
</script>
</head>
<body>

<div id="txtHint"><b>this will be updated</b></div>

</body>
</html>

The SetInterval won't run it. The php file is still only echo rand();. It worked at some point but I screwed something up I believe. Thanks in advance.

È stato utile?

Soluzione

setInterval() is likely running just fine, but showUser() is ending with an error since str is not defined. Check your JavaScript console for errors.

Either remove the reference to str, or define it somewhere.

Altri suggerimenti

try this:

 setInterval(function(){showUser()}, 1000);

Replace

setInterval(showUser, 1000);

with

window.onload = function() {
    setInterval(showUser, 1000);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top