0

I am only getting first time message and then code stop working.

I am newly learning long polling(I know,there gona be lot of errors and stupdity also ).Plz help.

Jquery function is here.

var timestamp = null;

var last_msg_id = 1;
  function chat(id, name) {

$('#chatcom').show('fast');
$.ajax({
    type:"Post",

    url:"load.php",
    data:{
        timestamp:timestamp
    },
  dataType:"json",

    async:true,
    cache:false,
    success:function(data) {

        var json = data;
        $("#chatcom").html(json['msg']);

        last_msg_id = json['last_msg_id_db'];

        timestamp = json["timestamp"];
    },
    error:function(XMLhttprequest, textstatus, errorthrown) {
        alert("error:" + textstatus + "(" + errorthrown + ")");
    }




});

}

load.php is here

$filename='data.php';

$lastmodif=isset($_POST['timestamp'])?$_POST['timestamp']:0;
$currentmodif=filemtime($filename);
$last_msg_id=$_POST['last_msg_id'];
$session=new $session;

$sql=mysqli_query($db3->connection,"SELECT * FROM chat_com where id>'$last_msg_id' ORDER by id ASC");

$sql_m=mysqli_query($db3->connection,"SELECT max(id) as maxid  FROM chat_com");
$row_m=mysqli_fetch_array($sql_m);
$last_msg_id_db=$row_m['maxid'];
$final_response=array();
if($last_msg_id_db>$last_msg_id){

    while($row=mysqli_fetch_array($sql)){
        $text=$row['mesg'];
        $fro=$row['fro'];
        $tocomr=$row['tocom'];

        $handle = fopen('data.php', 'a');
        fwrite($handle, $text);
        fclose($handle);

    }
}

while($currentmodif<=$lastmodif){
    usleep(10000);
    clearstatcache();
    $currentmodif=filemtime($filename);
}

$response=array();
$response['msg']=file_get_contents($filename);
$response['last_msg_id_db']=$last_msg_id_db;

$response['timestamp']=$currentmodif;
echo json_encode($response);
Aana Saeed
  • 299
  • 1
  • 4
  • 14
  • what are the error/s you are getting? "_I am only getting first time message_" **is this default message** or just the **first message sent**? – Jai Dec 07 '12 at 05:19
  • 1
    If `chat()` is called once, then it will respond once. For repeated long polling, the function needs to be called repeatedly. This will typically be done from the last line of the ajax success handler. – Beetroot-Beetroot Dec 07 '12 at 05:33

1 Answers1

0

you have to call your function again, so set a timeout function, within the success clause at the end,

success: function(data) {
      // your code....
setTimeout('yourfunction()',1000); // in your case it will be chat() function
}
Swarne27
  • 5,521
  • 7
  • 26
  • 41