I am trying to use the fetch() method to fetch
get.php to load messages:
The problem is: ( 1.) messages are duplicated or sometime triplicated when loaded.
(2)The messageBox container is stable, it can play uploaded video alright.
The scrolling is stable ,but the messages keep duplicating or triplicating.
(3) When a new message is submitted by the user the message is displayed twice.What can I do?
Here is my code.
get.php
header(‘ Content-type: application/json’);
$lastId=isset($_GET[‘last_id’])?intval($_GET[‘last_id’]):0;
$groupID=$_GET[‘clubid’];
$qry=”select *from grp_messages where grpID=’$groupID’ and Id>’$lastId’ order by Id asc “;
$result= mysqli_query($link,$qry);
$output =” “;
while ($row=mysqli_fetch_assoc($result)){
$msgId=$row[‘Id’];
$clubid=$row[‘grpID];
$gpname=$row[‘grpName’];
$userid=$row[‘id_user’];
$first=$row[‘firstname’];
$last=$row[‘lastname’];
$usernamd=$row[‘username’];
$member_photo=$row[‘userProfPhoto’];
$message=$row[‘messages’];
$sent_on=$row[‘created_at’];
$dateMod=$row[‘created_at_modify’];
$message_photo=$row[‘grpMsgPhotos’];
$message_video=$row[‘grpMsgVideos’];
$message_video_ext=$row[‘grpMsgExtentions’];
$profile_photo_path=”usersPphotos/”;
$message_photo_path=”grpChatPhotos/”;
$message_video_path=”grpChatVideos/”;
video_show=”grpChatVideos/$message_video”;
$trc=$message_photo_path.$message_photo;
$Tsrc=$profile_photo_path.$member_photo ;
$imagalt=”Loading Image ….”;
$redirect=
”<a id=”refN”href=”mem_profile.php?…….”>”;
If($message_video==” “){
$msgvideo=” “;
}
else{
$msgvideo = “
<video onerror=”this.style.display=’none’” id=’msg_videotag’ loop muted controls><source src=’$video_show’type=’video/$message_video_ext’> Your browser doesn’t support the video tag.
”;
}
if(($message_video !=’’)&&($message_photo ==’’ )){
$output.=””;
$output.=”
$redirect
$first $last:
$msgvideo$message
Sent:”.$dateMod.””;
$output.=””;
}
$lastId=$msgId;
}
echo json_encode([“last_id”=>$lastId,”messages”=>
$output]);
JavaScript script.js
messageBox= document.getElementById(‘messages’);
var clubID=document.getElementById(‘clubid’). value;
var lastMessageId=0;
setInterval(()=>{
var isAtBottom=messageBox.scrollTop + messageBox.clientHeight >=messageBox.scrollHeight-10;
fetch(‘get.php? last_id=’ + lastMessageId + ‘&clubid=’ + clubID)
.then(response=>response.json())
.then(data=>{
if(data.messages){
document.getElementById(‘contbox’).style.display=”none “;
var tempDiv= document.createElement(‘div’);
temDiv.innerHTML= data.messages;
lastMessageId=data.last_id;
var lastChild=tempDiv.lastElementChild;
var lastMsgId=lastChild? lastChild.getAttribute(‘data-id):null ;
Array.from(tempDiv.children).for each(msg=>{
var msgId=msg.getAttribute(‘data-id’);
if(!msgId.includes(lastMsgId+1)){
messageBox.appendChild(msg);
}
});
if(isAtBottom){
messageBox.scrollTop = messageBox.scrollHeight ;
}
}
})
},1000);