Quote:
Originally Posted by Punk
f I did that, how would I alert ajax that there is new data? I don't want to do a timer to just check for new content because I want this to be as real time as possible.
|
That's the key question, and you've really hit the crux of the issue, which is important. It's critical to understand that JavaScript can only receive information if it is asking for it: it can only make requests of the server, and will never be aware of anything new unless it asks for it repeatedly. However, you've rightly pointed out that having the browser on a loop which constantly asks for new information is not a good design scheme: especially with something as inefficient as JavaScript.
If you're going to use JavaScript as your client, it's better to issue only a single request at a time, then only when it receives a new chat message issue a new request. Do the "waiting for a new message" on the server side. And yes, you should be using the XMLHttpRequest object for this.
An XMLHttpRequest object will not complete until it has received a response from the server. Using this basic premise of HTTP protocol, you can eliminate a lot of overhead in the browser, which generally doesn't deal with repeated requests over a long period of time very well.
I've thought about this theory for a while, after observing this sort of behavior on a chat program I was using recently. I noticed that it was only using JavaScript to relay requests, so I Firebugged it to see what the requests looked like. I may write up a better theory of how this should function with PHP on the server side someday, but if you can figure it out yourself, you'll have a pretty cool chat client that's more efficient than what you would have if you forced the browser to connect to the server every few seconds.
Unfortunately PHP isn't going to be very adept on the server-side, if you keep all of your information inside the database. This is because PHP MySQL connections are single threaded, which means, to the best of my knowledge, they won't know about new information inside a single mysql_connect() session. This means you are probably going to have to keep the most recent messages inside of a file instead of the database, then push them to the database for long term storage when you're done with them.
The combination of JavaScript and PHP is probably not the most ideal situation for this sort of application, but with a little extra work it's possible to make something that's still good.
I've read a couple of articles about making chat programs with JavaScript and PHP, but they invariably seem to be about how to make constant requests from the browser, which I just feel is the wrong approach if you want something that responds instantly and doesn't create memory leaks.