0

I'am now developing web based chat like (example: startdevelop livehelp, zopim, etc) . I want to add module/feature that show both of admin and visitor "typing.. / is writing a message.." information.

I have insert jquery change/keyup function. But then? what should i do. Insert value that user "is typing" to database? and client browser always check in interval.

I think, that way can make server busy.

Is there better solution?

Thank you

2 Answers2

3

If you have a form with some elements:

<input type='text' id='textField' />
<textarea id='textarea'></textarea>

You can detect typing with:

$('#textField').change(function() {
    //report to the server
});

or

$('#textarea').keyup(function() {
    //report to the server
});

How your application handles and displays the 'typing' status is entirely dependent upon your application and database. My suggestion would be to use the typing events to trigger a database insert like this:

UPDATE tbl_chatrooms SET typingmoment = NOW() WHERE chatID = :chatID AND userID = :userID;

Then, your AJAX running at an interval would make a request to the server which would return data from a query that looks like this:

SELECT userID, IF(typingmoment > NOW() - INTERVAL 10 SECOND, 1, 0) AS typing FROM tbl_chatrooms WHERE chatID = :chatID;

Basically, this will return a 1 or a 0 for each user in the chat based upon whether they have typed anything in the last 10 seconds. You'd probably run your interval at 5 seconds or so.

Edit: This handles the basics, but as it sits, someone typing a 100 character message would end up sending 100 ajax requests to the server. Best to set a flag, then report to the server at an interval.

Something else to consider is to make sure your interval calls kill any active previous calls. Set the ajax call to a window. global variable, then you can abort it at the next interval, in case it's still running. That way, if there is a hiccup in your internet connection, or your internet connection is slow, you don't have a whole bunch of ajax requests piling up on a schedule. Have a look at this question to see how to cancel requests.

Community
  • 1
  • 1
Jerbot
  • 1,168
  • 7
  • 18
  • Thank you @SuperJet . That code is on front end side. I have no idea in server side code. What should i write in ajax code. Send value "typing" to database. And client browser always check (in interval) ? – Ahmad Oriza May 19 '14 at 05:18
  • I've updated my answer with a little SQL to help you get started. – Jerbot May 19 '14 at 12:34
3

You can catch keypress event on the textarea, and use setTimeout to detect when the user has stopped typing for a while.
Using AJAX you can send those events to the server for processing.
Check out these links:
http://api.jquery.com/keypress/
https://developer.mozilla.org/es/docs/Web/API/Window.setTimeout

ferow2k
  • 128
  • 4