0

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;
4

2 回答 2

0

You are assigning value outside of loop and because of that you are getting the last result. Assign the values inside loop.

$response = array();

while($row = mysqli_fetch_assoc($r)) {
    $nou = $row['f1'];
    $nru = $row['f2'];
    $response['msg'] = $row['content'];
    $response['timestamp'] = $row['time'];
}

echo json_encode($response);
于 2013-07-20T12:57:52.790 回答
0

Use array replace $ntext = $row['content']; with $ntext[] = $row['content'];

于 2013-07-20T12:59:20.660 回答