-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>
");
?>
3
  • 1
    You must use AJAX. Client-side code can't call server-side code except through an HTTP request. Commented Apr 16, 2017 at 20:22
  • 1
    "Don't really know AJAX that well." That is fairly easily remedied. Commented Apr 16, 2017 at 20:22
  • Also, calling setTimeout with a string parameter is bad practice. Use a function reference: var refresher = setTimout(refreshDiv, 2000); Commented Apr 16, 2017 at 20:31

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

10 Comments

Thanks for this - would the above code just be used like any other function in JS.
@SamBrown Just add it in a <script> block. When it works, be sure to accept an answer. Hope this was helpful!
How can I use the above code in my function refreshDiv()
Also what is yourDiv for in code
@SamBrown You don't need to, but you can just copy it into refreshDiv. Make sure you only call it once, though, because it's creating a timeout that will fire on its own once a second.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.