Long Polling

Hello everyone.

I’m trying to set up a long polling with php and ajax , retrieving data from mysql.
I looked at several post and tutorial, but I’m not able to work it out.
Here my code:



include "../connect.php";

$requestedTimestamp = isset ( $_GET [ 'timestamp' ] ) ? (int)$_GET [ 'timestamp' ] : time();

while ( true )

if (!$result = $cn->query("SELECT date,time, nameclient, emailclient  FROM shoppingcart WHERE time > $requestedTimestamp")) {
    echo "Errore della query: " . $cn->error . ".";

    // conteggio dei record
    $rows = $result->fetch_row();
    if ( count( $rows ) > 0 )
        $json = json_encode( $rows );
        echo $json;
        sleep( 2 );


function getContent( timestamp )
    var queryString = { 'timestamp' : timestamp };
    $.get ( '' , queryString , function ( data )
        var obj = jQuery.parseJSON( data );
        for (var k in obj)
            var comment = "<p>" + obj[k].comment + "</p>";
            var timestamp = obj[k].timestamp;
            $( '#response' ).append( comment );
        // reconecta ao receber uma resposta do servidor
        getContent( timestamp );
$( document ).ready( function ()


        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript" src="client/client.js"></script>
        <div id="response"></div>


Is there anyone who can help me ?

What actually happens with your code when you run it, and how does that differ from what you want it to do?

You only seem to retrieve one row from the result set in your PHP code, rather than retrieving all the rows that the query returns.

it doesn’t work at all.
When I run server.php directly, it displays the last entry , but when I run result.php it keeps looping , and it says “undefined” .Something like.


I think the problem is in client.js, but I’m not able to work it out.

The “undefined” part is because you’re trying to access undefined variables in your JavaScript code.

I tried a test version which just creates an array with a single row in the PHP (which is what your code is doing), and echoes the encoded version back to the JavaScript. I found that to display the contents of the array, my code needed to be like this:

var obj = jQuery.parseJSON(data);
  for (var k in obj) 
	alert(k + " " + obj[k]);

So you get back an array called obj which equates to the elements of the array that you produced in the PHP file.

As I read the code, you want it to keep looping, don’t you? Hence the repeated calls to getContent().

If possible, please discuss the PHP aspects in this topic, and the JavaScript in

Sorry, I hadn’t realised there were two threads running on the same thing.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.