Ahmad Oriza Ahmad Oriza - 3 months ago 39
PHP Question

What is best method to detect user typing at server side code. In web based chat app?

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

Answer

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.