2

So I created really simple chatbox in php. It works very good, but I had to set up script that is nonstop loading data from database to the chat window (not probably the most efficient way, that's why I am asking):

    <script type='text/javascript'>
    $('#chatbox').html('Loading...');
    $(document).ready(function() {
    setInterval(function(){loop()}, 0);
    function loop(){
     $('#chatbox').load('/chatbox.php');
    }

}); 
    </script>

And in chatbox.php:

include '/classes/class.chatbox.php';
$chat = new Chat();
$chatboxMsg = $chat->getNewMessages();
echo $chatboxMsg;

But this isn't the problem. My question is, how can I load the data (=refresh chat) for ALL users that have opened chat window, only when someone post new message (=insert new row to the db), without running script that is checking something every second?

user3560463
  • 149
  • 2
  • 10

3 Answers3

2

You need events generated by server.

The fastest and recommended solutions for that are based on:

Node.js

More possibilities using:

  • AJAX long polling
  • HTML5 Server Sent Events
  • HTML5 Websockets
  • Comet

Attached links and samples:

Community
  • 1
  • 1
Qarib Haider
  • 4,796
  • 5
  • 27
  • 38
  • This looks promising.. but it will probably take some time because I have never heard about these things (except Node.js, but I don't use it too). Anyway, thanks for suggestions, I hope I'll find solutions there. – user3560463 Jul 17 '14 at 10:27
  • @user3560463: I have updated my answer.. Yes, this is gonna take some time, but i would prefer going for node based solution, it is really sexy ;) – Qarib Haider Jul 17 '14 at 10:30
1

I think you will need listeners. Here is how you can implement them the best way: PHP Event-Listener best-practice implementation

Community
  • 1
  • 1
molerat
  • 946
  • 4
  • 15
  • 43
1

Check the socket.io. You will definitely find it to be the easiest way of doing it. When a new message arrises you can braodcast the message . Here are some of the references that you can use

Hope it helps

Community
  • 1
  • 1
Abdul Hamid
  • 3,222
  • 3
  • 24
  • 31