0

I have the following script at the bottom of my php page, it runs on pageload, but I need it running every 10 seconds. It only runs on page load.

PHP is running. I've tested this with a countdown from ten, and the script is actually looping, but for some reason not when i integrate this PHP.

Please help.

<script>
    var CurrentBranch = "<?php echo file_get_contents('gitstatus.txt'); ?>";

    var x = setInterval(function () {
        CurrentBranch = "<?php echo file_get_contents('gitstatus.txt'); ?>";

        document.getElementById("CurrentTestBranch").innerHTML = CurrentBranch;

        CurrentBranch = "";
    }, 10000);
</script>

Edit: The code does display the file contents the first time around. But does not refresh when I make a change and save it.

Harvey Fletcher
  • 1,167
  • 1
  • 9
  • 22

2 Answers2

2

Your PHP code is run only when the page loads. It generates string literals when it runs. These do not get updated when the interval function gets called repeatedly (because the PHP does not run again).

If you want to get new data from PHP you need to make new HTTP requests.

You could either reload the entire page, or use XMLHttpRequest (or fetch) to call a web service that gives you the data you want (Ajax is a useful search term).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
-1

PHP happens before HTML hits the server.

Look up setTimeout() javascript command. What you need to do is get javascript to call another php script, which checks and echoes your value.

Something like this (could be pseudocode, from memory):

setTimeout(function(){
    var CurrentBranch = $.get('/url/that/sends/value');
    // do something with your value, call a function, whatever
}, 10000);
delboy1978uk
  • 12,118
  • 2
  • 21
  • 39