我正在处理聊天应用程序,我正在尝试使用Ajax和setInterval
函数从数据库中检索消息以插入新消息,然后将其附加到聊天框中。
NB。聊天应用类似于Facebook聊天。只在两个用户之间聊天。
问题是聊天框不断刷新并显示来自两个用户的随机消息。我不知道为什么???
这是代码: 聊天链接是这样的: message.php?接收机=用户名
数据库结构:
CREATE TABLE IF NOT EXISTS `forum_inbox` (
`id_msg` int(11) NOT NULL AUTO_INCREMENT,
`sender_id` int(11) NOT NULL,
`receiver_id` int(11) NOT NULL,
`message` text NOT NULL,
`dateMsg` int(11) NOT NULL,
`seen` enum('no','yes') NOT NULL DEFAULT 'no',
`date_seen` int(11) NOT NULL,
PRIMARY KEY (`id_msg`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
messages.php
$sender_id = $_SESSION['id_userf'];
$receiver_id = get_username_id($_GET['receiver']);
$stmt = $PDO->prepare("SELECT * FROM `forum_inbox`
WHERE
(sender_id=? AND receiver_id=?)
OR
(sender_id=? AND receiver_id=?)
ORDER BY dateMsg ASC");
$stmt->execute(array($sender_id, $receiver_id, $receiver_id, $sender_id));
$messages = $stmt->fetchAll(PDO::FETCH_OBJ);
<div id="inbox-chat">
<section class="chat-container">
<ol class="chat-box" id="chat-box">
<?php foreach($messages AS $msg): ?>
<li data-messageid="<?php echo $msg->id_msg ?>">
<div class="messages">
<p><?php echo $msg->message ?></p>
<time datetime="time_stamp($msg->dateMsg);?>">
<?php echo time_stamp($msg->dateMsg);?>
<i class="fa fa-clock-o"></i>
<?php echo $msg->dateMsg; ?>
</time>
</div>
</li>
<?php endforeach; ?>
</ol>
</section>
</div>
tchat.js
timer = setInterval(newestMessages, 2000);
function newestMessages() {
/************************************************/
/* ***receiver*** value is passed from a hidden input /
/**********************************************/
var receiver = $(".receiver").val();
var newest_msg = $('.chat-box').children('li').last().data("messageid");
$.ajax({
url : 'ajax/inbox.php',
data : 'receiver='+receiver +'&newest_msg='+newest_msg ,
success : function(data){
$("#chat-box").append(data);
$('#chat-box').slimscroll({ scrollBy: '450px' });
}
});
}
inbox.php
ob_start();
session_start();
require_once '../../config/connect.php';
require_once '../../functions/func.php';
$sender_id = $_SESSION['id_userf'];
$receiver_id = $_GET['receiver'];
$last_msg = $_GET['newest_msg'];
$stmt = $PDO->prepare("SELECT * FROM `forum_inbox`
WHERE
(sender_id=? AND receiver_id=?)
OR
(sender_id=? AND receiver_id=?)
AND
id_msg > ?
ORDER BY dateMsg ASC
");
$stmt->execute(array($sender_id,$receiver_id,$receiver_id,$sender_id,$last_msg));
$messages = $stmt->fetchAll(PDO::FETCH_OBJ);
if($stmt->rowCount() > 0):
foreach($messages AS $msg):
echo '<li data-messageid="'.$msg->id_msg.'">
<div class="messages">
<p>'.$msg->message.'</p>
<time datetime="'.$msg->dateMsg.'">
<i class="fa fa-clock-o"></i>
'.$msg->dateMsg.'
</time>
</div>
</li>';
endforeach;
endif;