Can you help me with a detail in a chat application I’m programming in PHP and Ajax?

BHARAT GUPTA September 8, 2012
Pinterest Stumbleupon Whatsapp

I had thought of making a chat application in PHP & Ajax. For this I used a table ‘comments’ with the following fields: ‘from’, ‘to’, ‘time’ & ‘text’

Now say whenever user ‘A’ enters some text to send to user ‘B’, I am going to insert that in the table ‘comments’.

The question is: Does the script of user ‘B’ repeatedly need to check the database whether user ‘A’ has entered some text or not OR is it possible to notify user ‘B’ whenever some text is entered by user ‘A’

Please help me. Thank you!

Ads by Google

  1. Meeth Jain
    December 23, 2012 at 6:11 am
  2. illegal3alien
    September 13, 2012 at 2:23 pm

    The easiest way is to definitely poll the server. You can make a very small requests that sends the time of the last received message and the server will only respond if it has a new message since than. You can also change the rate at which the chat program polls the server based on how long it has been since it last successfully received a message.

    Like mentioned, there are ways to get the server to tell the client when there is a new message, but most require custom setups you may not be able to use (depending on the type of hosting you're using)

    • Bharat
      September 13, 2012 at 6:17 pm

      thanks @illegal3alien. you explained it quite nicely. your suggestion to send the time of the last received message is a real good one, i will take a note of it

  3. Andrew
    September 9, 2012 at 3:24 pm

    This is a pretty decent explanation.
    stackoverflow.com/questions/8629083/automatic-notification-in-database-change-similar-with-facebook-friend-request

  4. pulptunes
    September 9, 2012 at 1:34 pm

    Yes, you can repeatedly poll the table to see if there are new messages. That would be the easiest approach. But a cleaner, more performant, and less resource intensive method (yet much more complicated) would be to use a persistent connection between your server and your chat clients. This is achieved through html5 technologies such as Websockets or Server-Sent-Events. There's a popular javascript library called Socket.io that allows you to abstract all of this. I recommend you visit html5rocks.com and socket.io for more information.

    • Bharat
      September 10, 2012 at 5:00 pm

      thanks @pulptunes i will surely give a look to this

      anybody else with any diff idea, please post that idea here

Ads by Google