2

How do I make it so that my javascript only gets info from my database when its updated?

For example :

Let's say im programming a chat system and I only want the messages that are sent to the chat database after the user has logged onto the website to display in his chat box.

Meaning maybe Bob types a message and its sent to everyone on the website at that moment. John enters the session a while later and does not get the message.

I want that to happen ^

I currently have a javascript on interval getting data from the database every second but that causes the entire history of messages to be displayed in the user's textbox. Can anyone help me with this? Greatly appreciated.

 function getMessages(){
  $.get('GetMessages.php',function(data){
   $(".chatMessages").html(data);

  });
 }

 setInterval(function(){
  getMessages();
 },500);

EDIT 1

No, I don't can't use long polling as I'm using apache to host it and i doubt i can mount socket.io onto apache :/

is there no other method?

  • 1
    Pass a parameter like "identifier of most recent message the user is looking at" to let the back-end script know where to start from. – apokryfos Jul 07 '17 at 12:34
  • I think this is a duplicate. You can do this with `long polling` (https://www.pubnub.com/blog/2014-12-01-http-long-polling/) or `websockets` (https://socket.io/). The stackoverflow question: https://stackoverflow.com/questions/11077857/what-are-long-polling-websockets-server-sent-events-sse-and-comet – Philip Jul 07 '17 at 12:35
  • Possible duplicate of [What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?](https://stackoverflow.com/questions/11077857/what-are-long-polling-websockets-server-sent-events-sse-and-comet) – Igor Jul 07 '17 at 12:36
  • 1
    add a time-reference field on messages and users then compare these 2 fields in your query and get the appropriate messages for the "newly logged in"user. – taha Jul 07 '17 at 12:38
  • NOT QUESTION RELATED. consider implementing your chatapp with node and socketio (much more efficient and easier). – taha Jul 07 '17 at 12:41

0 Answers0