-2

Don't really know AJAX that well.. Here is the issue.

I am reading a database within the PHP function that populate some global variables, I can access the variables ok, but I need the php function to be called regularly.

<?php

function thatIwant()
{
  //read database
 return 10;
}

echo("
<script>

function refreshDiv()
    {
     //// this is where I need to call the above function.
     var refresher = setTimeout('refreshDiv()', 2000);
    }
</script>
");
?>
furkle
  • 5,019
  • 1
  • 15
  • 24
Sam Brown
  • 1
  • 1
  • 1
  • 1
    You must use AJAX. Client-side code can't call server-side code except through an HTTP request. – 4castle Apr 16 '17 at 20:22
  • 1
    _"Don't really know AJAX that well."_ [That is fairly easily remedied.](https://learn.jquery.com/ajax/) – Alex Howansky Apr 16 '17 at 20:22
  • Also, calling `setTimeout` with a string parameter is bad practice. Use a function reference: `var refresher = setTimout(refreshDiv, 2000);` – 4castle Apr 16 '17 at 20:31

1 Answers1

1

You can't call a PHP function regularly from Javascript without the use of an XmlHttpRequest. PHP is executed when the page is first requested. With an XHR, you could do the following:

function refreshDiv() {
    setTimeout(function() {
        var xhr = new XmlHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState === 4 && this.status === 200) {
                document.getElementById("refreshDiv").innerHTML = 
xhr.responseText;
            }
        };

        xhttp.open("GET", "yourPHPEndpoint.php", true);
        xhttp.send();
    }, 1000);
}

This would allow you to query your PHP file continuously, and update the contents of the div with the result of the query. This can also be done through jQuery with $.ajax or $.get.

furkle
  • 5,019
  • 1
  • 15
  • 24