Update PHP function every second

Asked

Viewed 765 times

0

I am using a function to get the server load:

function get_server_cpu_usage(){
    $load = sys_getloadavg();
    return $load[1];
}

I call her with:

<div id="load"><?= get_server_cpu_usage(); ?></div>

I need to implement something to update this information every second, without the page being updated, something like JS setTimeout or setInterval.

How can I do that in this case?

2 answers

2


You will have to create a separate PHP (cpu.php):

    $load = sys_getloadavg();
    echo $load[1];

In the header (HEAD) of HTML:

<script>
window.onload = cpuUsage();
function cpuUsage(){
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
           document.getElementById("cpu_usage").innerHTML = xhttp.responseText;
        }
    };
    xhttp.open("GET", "filename", true);
    xhttp.send();
    //Repetir após 5 segundos
    setTimeout(function(){ cpuUsage(); }, 5000);
}
</script>

In the body (Body) of HTML:

<div id="cpu_usage">-----</div>

I advise later to improve this part PHP by putting an authentication method avoiding overload or direct access of the file, can be accessed only by AJAX with a correct GET parameter or method token.

0

So directly, as the function you want is on the back, it will not be possible. To solve, you can put this function to execute a separate script and call with an ajax.

For example (or something like that):

$.get('http://teste.com.br/funcao.php', function(){

});
  • Is there only this way? There is no way to do it directly on the page?

  • Not in this case. See, your role was written in PHP, right? PHP runs in the back end. JS runs on the front. Actually, on the client. There is no way JS can interfere or call PHP directly. In this way, I do not know if it is feasible, but either you call as I motrei or do this function again but in js.

  • It is an architectural problem of the WEB itself. How it works.

  • How do I convert this function to JS?

  • Well from what I’ve seen, you take information from the server, don’t you? Anyway, as this info you will only get from the server side, I would return it in JSON format, only the information you want to display. In the ajax request, I would receive the information and display, or do whatever I wanted. Then yes, with the time interval you want. Unfortunately, it’s the only way to do it without postback

Browser other questions tagged

You are not signed in. Login or sign up in order to post.