Update PHP function every second

0

I'm using a function to get the server load:

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

I call it 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 the setTimeout or setInterval of JS.

How can I do this in this case?

    
asked by anonymous 05.03.2018 / 21:28

2 answers

2

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

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

HTML HEAD heading:

<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 HTML body :

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

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

    
05.03.2018 / 23:56
0

So directly, since the function you want is in the back, it will not be possible. To resolve this, you can put this function to execute a part script and call with an ajax.

For example (Or something like this):

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

});
    
05.03.2018 / 21:37