Search code examples
javascriptjqueryajaxchatlong-polling

Simple chat working but display same messages over and over


My question is how do i stop the loop over and over on the same messages?

Here is my code:

waitForMsg();
setInterval(waitForMsg, 5000);

function waitForMsg() {
  $.ajax({
    url: CI_ROOT + 'welcome/getMessage',
    type: "GET",
    dataType: 'json',
    async: true,
    cache: false,

    success: function(data) {
      $.each(data, function(key, value) {

        var msg_id = value.msg_id;
        var timestamp = value.posted_at;
        var user_msg = value.msg;
        var user_name = value.name;


        $(".chat_log").append(
          "<p data-id=" + msg_id + ">" + "<b>" + user_name + "</b>" + ': ' + user_msg + ' | Posted: ' + "<span data-livestamp=" + timestamp + "></span>" + ', msg ID: ' + msg_id + "</p>"
        );


      });
    }
  });
}

Here is from where i get "welcome/getMessage":

[{
    "name": "Dima",
    "msg": "i don't know i feel bad today :(",
    "posted_at": "2015-08-29 02:50:31",
    "msg_id": "12"
  },
  {
    "name": "toma",
    "msg": "whats wrong?",
    "posted_at": "2015-08-29 02:48:59",
    "msg_id": "11"
  },
  {
    "name": "toma",
    "msg": "hey",
    "posted_at": "2015-08-29 02:46:11",
    "msg_id": "10"
  }
]

And result is:

Dima: i don't know i feel bad today :( | Posted: 3 hours ago, msg ID: 12
toma: whats wrong? | Posted: 3 hours ago, msg ID: 11
toma: hey | Posted: 3 hours ago, msg ID: 10
Dima: i don't know i feel bad today :( | Posted: 3 hours ago, msg ID: 12
toma: whats wrong? | Posted: 3 hours ago, msg ID: 11
toma: hey | Posted: 3 hours ago, msg ID: 10
Dima: i don't know i feel bad today :( | Posted: 3 hours ago, msg ID: 12
toma: whats wrong? | Posted: 3 hours ago, msg ID: 11
toma: hey | Posted: 3 hours ago, msg ID: 10
Dima: i don't know i feel bad today :( | Posted: 3 hours ago, msg ID: 12
toma: whats wrong? | Posted: 3 hours ago, msg ID: 11
toma: hey | Posted: 3 hours ago, msg ID: 10

I need somehow to compare msg id in client side and or server side.

I would be glad for any help thanks!

Dimak.


Solution

  • Here is my new solution.

    https://jsfiddle.net/dannyjhonston/tvcy4k6r/1/

    Updated...

    $(function() {
      var messages = [{
        "name": "Dima",
        "msg": "i don't know i feel bad today :(",
        "posted_at": "2015-08-29 02:50:31",
        "msg_id": "12"
      }, {
        "name": "toma",
        "msg": "whats wrong?",
        "posted_at": "2015-08-29 02:48:59",
        "msg_id": "11"
      }, {
        "name": "toma",
        "msg": "hey",
        "posted_at": "2015-08-29 02:46:11",
        "msg_id": "10"
      }];
    
      $("#btnSendMessage").on("click", function() {
        // Adds new message object to message's array.
        messages.push({
          name: "NewUser",
          msg: $("#txtMessage").val(),
          posted_at: new Date(),
          msg_id: new Date().getTime()
        });
        console.log(messages);
      });
    
      var oldCountMessages = messages.length; // Previously, you need to save the messages's length.
    
      var newMessageIndex = 0; // Declare a numeric variable to use like new index to show a new chat message.
    
      // You need to print the messages, only once.
      for (var i = 0; i < messages.length; i++) {
        $("#chatMessages").append("<div class=\"chat\"><span class=\"user\">" + messages[i].name + "</span><br /> " + messages[i].msg + "</div>");
      }
      // Self-looping function to show check if there are new messages.
      (function loop() {
        // Checking if there are new messages.
        if (messages.length > oldCountMessages) {
          // Initializing newMessageIndex with the new message index, to show it.
          newMessageIndex = messages.length - 1;
          // Printing only the new message.
          $("#chatMessages").append("<div class=\"chat\"><span class=\"user\">" + messages[newMessageIndex].name + "</span><br /> " + messages[newMessageIndex].msg + "</div>");
        }
        // Updating oldCountMessages variable for the next verification in the looping function.
        oldCountMessages = messages.length;
        setTimeout(loop, 1000); // Checking the server every second.	
      })();
    });
    #chatMessages {
      font-family: sans-serif;
      font-size: 0.8em;
    }
    
    .chat {
      background-image: linear-gradient(#BED4E6, #FFFFFF);
      border: solid 1px #84A8D6;
      border-radius: 5px;
      margin: 5px;
      padding: 10px;
    }
    
    .chat:hover {
      background-image: linear-gradient(#FFFFFF, #BED4E6);
    }
    
    .user {
      background-color: inherit;
      color: #224577;
      font-weight: bold;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <input id="txtMessage" type="text" value="" />
    <button id="btnSendMessage" type="button">Send message</button>
    <hr />
    <div id="chatMessages"></div>