Search code examples
javascriptphpajaxxmlhttprequest

Repeat PHP function every 2 seconds


So I have a code, where a number is retrieved from a text file and is displayed through HTML.

The thing is that it only retrieves the number when I refresh the page. If I change the number on other page, it doesn't change on the other page.

I've seen similar questions before, most of them said to use AJAX, but I don't understand much about AJAX and I only need it for this bit of code, it's not like I'm going to constantly use it. I would like to know if there is any other besides AJAX and if there is only AJAX, please present examples of code.

PHP code:

<?php
    $file = "num.txt"; //Path to your *.txt file
    $contents = file($file);
    $num = implode($contents);
?>

JavaScript code. Basically it gets the PHP value and outputs to the html.

document.getElementById("num").innerHTML = '<?php echo $num; ?>';

Keep in mind, I don't want to refresh the page. Just the variable.


EDIT: PHP code - Getting an error - Notice: Undefined index: keynum in C:\xampp\htdocs\num.php on line 3

Here is the code of the PHP

<?php
    $keynum = $_POST['keynum'];
    $post = "INSERT INTO post (keynum) VALUES ($keynum)";
    $fileLocation = getenv("DOCUMENT_ROOT") . "/num.txt";
    $file = fopen($fileLocation,"w");
    $content = $keynum;
    fwrite($file,$content);
    fclose($file);
    echo 'Response';
    die();
 ?>

Solution

  • get_nbr.php

     <?php
     $file = "num.txt"; //Path to your *.txt file
     $contents = file($file);
     $num = implode($contents);
     echo $num;
     ?>
    

    index.php

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <!---trigger get_nbr() on page load on an infinite loop every two seconds -->
    <body onload="setInterval(get_nbr, 2000)">
    <script>
      function get_nbr() {
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
      document.getElementById("num").innerHTML = this.responseText;
      }
      };
      xhttp.open("GET", "get_nbr.php", true);
      xhttp.send();
      }
     </script> 
    <p id="num"></p>