1
<?php
  echo '
    <script type="text/javascript">
      $(function() {
        var refresh = setInterval(function() {
          $("#content").html("'.rand().'");
        }, 3000);
      });
    </script>

    <div id="content"></div>
  ';
?>

This will update the div "content" with a random number after 3 seconds, however it only updates once. Why does it not continually generate a new number every three seconds, and how can I make it do precisely that?

Thank you in advance for any assistance rendered.

Free Consulting
  • 4,300
  • 1
  • 29
  • 50
daveycroqet
  • 59
  • 3
  • 8
  • 1
    View the page source in the browser, and you will see what it really does, and that the update part works just fine... – Guffa Mar 23 '11 at 22:50

1 Answers1

5

Ha. PHP is run on the SERVER side. JS is on the client.

you need to generate the rand on the JS side not he php side...

js code:

<script type="text/javascript">
  $(function() {
    var refresh = setInterval(function() {
      var randomnumber = Math.floor(Math.random()*11);
      //where 11 dictates that the random number will fall between 0-10
      $("#content").html(randomnumber);
    }, 3000);
  });
</script>

<div id="content"></div>
Naftali
  • 144,921
  • 39
  • 244
  • 303
  • Wouldn't 11 dictate that it falls between 0 and 11, not 10? For example, if the Math.random() value was 0.99, then the value would become 10.89, which is not between 0-10. – Peter Olson Mar 23 '11 at 22:49
  • @Peter, the Math.floor, rounds it down to 10 (is it is 10.89) – Naftali Mar 23 '11 at 22:51
  • Thank you for the prompt response. So then is there no way to pass PHP variables and have it continually update? I'm trying to make this AJAX-ish, and jQuery's .load isn't doing the trick for me. – daveycroqet Mar 23 '11 at 22:56
  • lol thats not ajax. make another question about ajax if you want. but for what you want above, this is the answer u need ^_^ – Naftali Mar 23 '11 at 22:57