0

So, I have some javascript code someone gave me that refreshes part of a page, and it works by refreshing a variable with a random number assigned to it. but when I try to refresh php code in it it will only run once. Why is this? Is there a way I can remedy this problem?

//other working php code

if(isset($_POST['hostgame'])) 
    {

//do some stuff
print"<div id='target'> </div>";

    }

<script >

setInterval(function refresh(){
      // why isn't this refreshing? math.random is?

    <?php
      $query = "select * from gameStatus".$_SESSION['gamenumber'];
      $result = mysqli_query($link, $query);

        while($row = mysqli_fetch_row($result))
        {            
            list($id, $status) = $row;
        }
      $gameStatus=$status;
    ?>      

  var value = "<?php echo $gameStatus; ?>"+Math.round(Math.random()*100);

  $('#target').addClass('hidden');
  $('#target').html(value);
  $('#target').removeClass('hidden');} , 1500);

  </script> 
</body>
</html>

so the gamestatus gets printed out the first time but doesn't get refreshed to show its latest changes in mysql. I checked the database and it is being changed, but not showed on screen. the random number is refreshing though. Can someone explain why? maybe how to fix it?

2316354654
  • 279
  • 2
  • 3
  • 14
  • 2
    If you want it to refresh after the page has been "served", this is because the PHP has done it's done, it has served the page, the only way to get the PHP to "refresh" is to force a reload of the whole page (AJAX is also an option, but this is the only way to do it on page), i.e. request it from the server, this is because JS is client side (affects after load) and PHP is server side (runs before the page is loaded / displayed) – Can O' Spam May 21 '18 at 15:26
  • 1
    Why do you have php code without the tags ? – Roy Bogado May 21 '18 at 15:27
  • 1
    The PHP code only runs once before the page is given to the client. – Carcigenicate May 21 '18 at 15:27
  • 1
    Sadly you can't use php in the javascript like this. Look into AJAX https://www.w3schools.com/xml/ajax_intro.asp – Michael Beeson May 21 '18 at 15:28

0 Answers0