For school I had to create a AJAX/PHP based chatbox where someone can just join in by entering their username and presses click. I got it all working but I got some questions whether the way I did this is the right way to do it.
One question by example is that I am using a setInterval from javascript to fetch the latest 5 records out of the database every second. But what if someone changes this interval on the website itself? And makes it so it queries the database every second? I was thinking of storing the last executed query date and check if it actually is the 1 second that I had set. But where would I store this? I wouldn't want to store it in my database most likely as I will have to query the database then also.
Another question is, do professional chat boxes actually use a interval to check for new records in the database in an x amount of time? If not, how do they go about it?
ATM I am at a point that I don't exactly know how I should go about this, is there an experienced PHP developer out there that could give answers on any of these?
Request the server once every 5 second (with or without database query) is expensive and does not scale. Instead of having client requesting every fixed interval, let the server notify the client whenever there is new message. To do so, you need a more persistence connection. There are two popular approaches:
Ajax Long Polling: usually, web server will close its connection once it has successfully serve the content. The idea behind long polling is to keep the connection open for long period of time and serve content by chucked. Once there is new message, it feed to client. Once the connection timeout, it re-open a new connection.
WebSocket: WebSocket allows web browser and server to have persistence connection via its WebSocket protocol (similiar to HTTP protocol). Some browsers does not support this feature yet.