I have two PHP scripts. One acts as a backend, and contains a class definition with some functions in it that show things like the computer's load average and RAM usage. The other acts as a frontend, which calls those functions and prints them along with some HTML and CSS to make it look nice. This works fine, but it doesn't update itself unless you refresh the page.
I made the backend able to return JSON tables of one function at a time, using the following code:
<?php
if (!empty ($_GET['q']))
{
$status = new status();
$query = $_GET['q'];
$data = $status->$query();
exit (json_encode($data));
}
?>
And I receive the data using JavaScript like so: (I am not using any frameworks)
function update_load()
{
var prefix = "Load average: ";
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var json = JSON.parse(xmlhttp.responseText);
document.getElementById("loadavg").innerHTML = prefix + json.load;
}
}
xmlhttp.open("GET", "./backend.php?q=load", true);
xmlhttp.send();
setTimeout ("update_load()", 10000);
}
The JSON response the page gives is valid:
{"model":"Intel Xeon 5150 @ 2.66GHz","load":"0.00 0.02 0.05"}
I have another function update_ram()
which is nearly identical and runs at exactly the same time. Both of these functions run on page load and work fine usually on the first time they run. Sometimes though, one of them (usually the load average) will stop working and instead display "undefined" and never update itself again. I put in an alert (xmlhttp.response)
into both functions, and the backend script looked like it was sending the table for the update_ram()
to both of the functions.
I tried delaying one of the functions by one second on page load, so now this problem happens less often, but it still happens. I suppose I could have it return the functions I want all at once, but then it would lose some reusability. What could be causing this and what can be done to fix it?
Or, is there an entirely different way I should be doing this?