Using setInterval
, you can repeat the execution of a function:
setInterval(function() {
console.log("test");
}, 1000);
As for your function body, bear in mind that the PHP is executed once only. If you wish to update the table, you need to:
- make an AJAX call to your backend server or any other service that will provide the current state of the table's contents
- modify the DOM of the table
The frontend code for the AJAX call could look like this:
setInterval(function() {
var xhr = new XMLHttpRequest();
xhr.onload = function(data) {
// DOM manipulation goes here
};
xhr.open("get", "/tableContents.php", true);
xhr.send();
}, 1000);
As for the DOM manipulation part, this depends on what format your PHP backend will return. Let's assume it's this JSON:
[
{"value": 10, "label": "foo"},
{"value": 20, "label": "bar"}
]
The DOM manipulation could look like this:
function(data) {
var i, j = data.length, html = "";
for(i = 0; i < j; ++i) {
html += '<tr><td>' + data[i].label + '</td><td>' + data[i].value + '</td></tr>';
}
document.getElementById("myTableContents").innerHTML = html;
}
In short: iterate over the server's response and build the new HTML. Then, replace the old HTML with the new one.
The above also assumes your HTML already contains a matching table:
<table>
<thead>
<tr>
<th>Label</th>
<th>Value</th>
</tr>
</thead>
<tbody id="myTableContents"></tbody>
</table>
Of course, the backend could as well generate a ready HTML, in which case the parsing of the returned data is not needed at all - you just replace the HTML.
Also, as a side note: I would advise against making HTTP requests every second; in case of a high traffic moment, the server could take longer than a second to respond, in which case you'd effectively flood it with requests it wouldn't manage to handle effectively. Calling the new request in the previous request's callback might be a better idea - this way you'd guarantee that a new request is sent only after the previous one has already been handled.