I am trying out long polling and it works with textfile but I can't make it return everything from a table.
var timestamp = null;
function waitForMsg() {
$.ajax({
type: 'GET',
url: 'update.php?timestamp=' + timestamp,
async: true,
cache: false,
success:function(data) {
// alert(data);
var json = eval('('+data+')');
if (json['msg'] != '') {
$('div.alltext').html(json['msg']); // MD
}
timestamp = json['timestamp'];
setTimeout('waitForMsg()', 1000);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// alert('error '+textStatus+'('+errorThrown+')');
setTimeout('waitForMsg()', 1000);
}
});
}
update.php
$filename = 'test.txt';
$lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$currentmodif = filemtime($filename);
while ($currentmodif <= $lastmodif) {
usleep(10000);
clearstatcache();
$currentmodif = filemtime($filename);
}
// how to rewrite the following?
$response = array();
$response['msg'] = file_get_contents($filename);
$response['timestamp'] = $currentmodif;
echo json_encode($response);
How do I rewrite the last part to get everything from a DB table?
EDIT:
I tried the following but it only returns one result and not the newest one but the one before.
$response = array();
while($row = mysqli_fetch_assoc($r)) {
$nou = $row['f1'];
$nru = $row['f2'];
$ntext = $row['content'];
$ntime = $row['time'];
}
$response['msg'] = $ntext;
$response['timestamp'] = $currentmodif;