Jake Jake - 1 month ago 7
HTML Question

How to Echo Updating Variable in PHP

Thanks for coming to try and help me solve my problem!

My problem is, I would like the display a variable on my page using PHP. This variable updates every second or so. I would like this to update on the page as the variable changes.
I tried using a while loop but this just continuously prints the variable. I will warn you, I am not very PHP savvy, and you're probably going to have to explain your answer to me, A LOT. Sorry I didn't include any code samples.. I didn't really think it was needed for this question. If you would like me to provide some samples, I will though. Thanks for considering answering my question! :)

Answer

You try to do something which is not so easy to implement with the basics of PHP. PHP is once generated on the server side and then gives the result to the client. (your browser). If you like to change the HTML Code dynamically you should take a look at JavaScript. This will allow you to make dynamic updates without reloading the page. (e.g. a user presses a button or a timer in your case):

var i = 1;

// update site content every second
setInterval(function() {

  // get div with id example
  var myElement = document.getElementById('example');

  // count up by 1
  i++;

  // update content
  myElement.innerHTML = 'Zahl ' + i;

}, 1000);
<html>

<head>
  <meta charset="UTF-8">
  <title>JavaScript test</title>
</head>

<body>
  <div id="example">Zahl 1</div>
</body>

</html>

Now if you would like to run a PHP Script every second you need something else which is called AJAX. So for example if you would like to run hello.php every one second and set the result of it to the same div from before you need this code:

var i = 1;

// update site content every second
setInterval(function() {

  // run function loadDoc every second
  loadDoc();

}, 1000);

function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    // get div with id example and update HTML
    document.getElementById("example").innerHTML = this.responseText;
  };
  xhttp.open("GET", "hello.php", true);
  xhttp.send();
}
<html>

<head>
  <meta charset="UTF-8">
  <title>JavaScript test</title>
</head>

<body>
  <div id="example">Zahl 1</div>
</body>

</html>

Comments