仅在有人提交新邮件时加载数据

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?

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:

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

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