not able to handling ajax request from a small chat module

孤者浪人 提交于 2019-12-25 04:03:48

问题


i am developing a simple chat module for my client, but not able to handle loop from setInterval()

Here is the js code from which i sending the request to get the data from the database

function getData(){

    jQuery.ajax({
        url: '../../get_data.php',
        data: 'to=<?php echo $_SESSION['ch_usr_id']; ?>',
        cache: false,
        success: function(data){
            jQuery('<div>'+data+'</div>').appendTo("#ch-data-con");
            setInterval("getData()", 5000);
        }
    });
}

and here is the get_data.php file which produce the data according to request

require "../../support/connection/connect_gib.php";

$to = addslashes(trim($_REQUEST['to']));

$query = "select * from chat where 
          guest_id='".mysql_real_escape_string($to)."' order by id asc";
$result = mysql_query($query);

while( $row = mysql_fetch_assoc($result) ){
    echo "<b>".$row['frm']." : </b> " .$row['message'] . "<br />";
}

i got the result in loop like all the data repeat again and again, but i want the newly updated data, please make me correct what i did wrong..


回答1:


You are using appendTo function in jQuery.. So all chat messages will be appended after old list. You can use .html() function to replace complete data.

Another way is to get only last chat message from php side, so all data will not be repeated. You can use auto id to point which messages are fetched last.




回答2:


You should preserve the last id fetched and use that for new request. And on server side you should fetch from there.

$id= addslashes(trim($_REQUEST['id']));
$query = "select * from chat where 
          guest_id='".mysql_real_escape_string($to)."' AND id > '".mysql_real_escape_string($id)."' order by id asc";

function getData(){

jQuery.ajax({
    url: '../../get_data.php',
    data: 'to=<?php echo $_SESSION['ch_usr_id']; ?>&id=' + last_id_fecthed,
    cache: false,
    success: function(data){
        jQuery('<div>'+data+'</div>').appendTo("#ch-data-con");
        setInterval("getData()", 5000);
    }
});

}



来源:https://stackoverflow.com/questions/10613268/not-able-to-handling-ajax-request-from-a-small-chat-module

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!