如何使用反向ajax

I heard about reverse-ajax or comets and thought of implementing it in my chat system.

Previously i had to do this stuff.

AJAX

updatePulls();
function updatePulls(){
        $.post('resource/php/pull.php',{
            latest_id : latest
        }
        ,function(data){
            ...
            }
            setTimeout(updatePulls,5000);   //5 seconds
        },'json');
}

PHP

...

    $user_id = $_SESSION['user_id'];
    $data = mysqli_query($con,"SELECT * FROM messages WHERE message_id > $latest_id AND ... ");
... 
  /*
    while($row = mysqli_fetch_assoc($data)){} and other stuffs
    and finally return at every call from client
  */
  echo json_encode($data);

Now after i heard about coments i thought of implementing it but can anyone show me how can i do that ? It says about making an indefinite loops and then i come to do this but i aint pretty sure about that.

COMET PHP

...

    $user_id = $_SESSION['user_id'];
    $data = mysqli_query($con,"SELECT * FROM messages WHERE message_id > $latest_id AND ... ");
... 
  while($anythingnew < 1 ){
     //again mysqli_query and  increment $anythingnew accordingly
   }
   /* 
    while($row = mysqli_fetch_assoc($data)) and other stuffs
    and finally return at every call from client
  */
  echo json_encode($data);

Any help please.