Click here to Skip to main content
15,895,538 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am working on a project,as am trying to check new inserted messages in db for each user and echo that when the user is chatting with another without refreshing the page to see the new message,but i try using setInterval but the problem is that once the user login the all messages will display for 3 seconds and disappear from the chat.
i used .html(),but when i use .append() it append same messages every 3 seconds please i need help on how to solve this i want it be working like facebook chat.

What I have tried:

this my jquery ajax request and the feedback code

JavaScript
setInterval(function(){
	var id = $(".id").val();
	  //alert(id);
	  $.ajax({
  type:'get',
   url:"msg.php",
   data:{id:id},
   success: function(data){
   $("#msgnot").append(data);
   // $("#msgnot").html(data);
   }

});
    },3000);


HTML
msg.php


<?php 
   session_start();
   include 'db.php';
   
   if(isset($_GET["id"])){
     $ids = $_GET["id"];
	    $sql = "select * from answers where userid='$ids' and msgstatus='0'";
       $query = mysqli_query($con,$sql);
       while($rows = mysqli_fetch_assoc($query)){
	 
	  ?>
	  <div id="reply"><a href="read.php?id=<?php echo $rows["id"]; ?>"><?php echo "message from ".$rows["replyid"]; ?>
	  <div id="m_active">
	  <?php
         if($rows["msgstatus"] == "0"){
		       echo "">"."1"."<br>";
		 }else{
		 }
		} 
		 }
	  ?></a></div></div>
Posted
Updated 15-Aug-17 20:44pm
Comments
SrikantSahu 15-Aug-17 3:46am    
Do you bring all the messages send to the user in each ajax call.. or its just the last message?
alertfrancis 15-Aug-17 13:11pm    
all the messages

1 solution

Hi,
If you bring all the messages then you can do a check whether the incoming message is same as the exiting one.. if not then only update/append it in the success function. Also you trim to cut out the spaces.

JavaScript
success: function(data){
   if(data != $("#msgnot").text()){
      $("#msgnot").append(data);
    }
   }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900