Creating a chat script with PHP and Ajax, Part 1
(Page 2 out of 4)Creating the server
Let's start by creating the server, but first, create a new database to hold the messages of your chat script, with the following database scheme:
`messageid` int(5) NOT NULL AUTO_INCREMENT,
`user` varchar(255) NOT NULL DEFAULT '',
`message` text NOT NULL,
`datetimestamp` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`messageid`)
) TYPE=MyISAM AUTO_INCREMENT=1 ;
The first thing the server must do is check what the client wants: adding a new message or requesting latest messages? The following code does what we want:
die('This chat server can only be used by the chat client.');
}
$action = $_GET['action'];
if ($action != 'get' AND $action != 'add') { $action = 'get'; }
// Do we want to get chat messages or add a new message?
if ($action == 'get') {
// Get messages
send_messages();
} else {
// Add a new message
add_message();
}
As you can see we're going to use two different functions: send_messages() to return all the latest messages and add_message() to add a new message.
Adding a new message is quite simple, and it only requires some standard database code, like this:
global $db;
// Everything there?
if (!isset($_GET['user'])) {
die('error:no-user');
}
if (!isset($_GET['message'])) {
die('error:no-message');
}
$user = ss(htmlentities(strip_tags($_GET['user'])));
$message = ss(htmlentities(strip_tags($_GET['message'])));
$datetimestamp = time();
// Insert message
$db->query ("INSERT INTO message (user, message, datetimestamp) VALUES ('$user', '$message', $datetimestamp)");
// Return any new message
send_messages();
}
The function first checks if both variables are there, and if they're not, it returns an error. The errors look a bit weird, but this format actually makes it easier for our client (you'll see why later). When everything is okay, the message is inserted into the database.
Note that the $db variable comes from a mysql class, which can be downloaded here: mysql.php.
The send_messages() function has to send the messages that have NOT yet been received by the client. To do this, the client sends the timestamp of the last received message, from which the server can automatically select the messages that haven't been received yet, like so:
global $db;
// Is there a latest timestamp?
if (!isset($_GET['latest'])) {
$latest = false;
} else {
$latest = intval($_GET['latest']);
}
// If there isn't a latest, get the five newest messages, and return them
if ($latest == false) {
$messages = $db->sql_query ("SELECT user, message, datetimestamp FROM message ORDER BY datetimestamp DESC LIMIT 0,4");
} else {
$messages = $db->sql_query ("SELECT user, message, datetimestamp FROM message WHERE datetimestamp > $latest ORDER BY datetimestamp DESC LIMIT 0,9");
}
// Any messages?
if ($messages == false) {
die('no-messages');
}
// Get newest timestamp
$newest = $messages['0']['datetimestamp'];
// Reverse array for correct order
$messages = array_reverse($messages);
// Return response
$response = $newest;
foreach ($messages as $message) {
$response .= $message['user'] . '>' . $message['message'] . "\n";
}
$response = trim($response);
die($response);
}
This code first selects the right messages, and after that returns it in the right format (each message is separated by a newline, and the user and message are separated by >).
That's all the code we need for the server, and if you combine everything together, you get the following file: chatserver.php.
Let's create the client now.
January 10th, 2006 at 6:07 pm
this script is shit, i’ve been trying to make it work but still “undefined error” … learn to code in register global @ off, make it work and give a .zip of your “working” chat and we will see.
January 10th, 2006 at 6:24 pm
I always code with auto_globals off, and my error reporting is set to E_ALL & E_STRICT. The ‘undefined error’ you’re seeing is probably a JS error, which has absolutely nothing to do with ‘globals’.
Secondly, the script does work, and all the parts can already be downloaded, including the chatserver PHP script.
January 10th, 2006 at 7:41 pm
I like how your name is nobody, would you like to add that you know nothing? I would just to save us all some time. At the very least you could exhibit some resemblance of respect for a person providing knowledge to the community.
January 11th, 2006 at 5:26 pm
I’ve parsed through this code many times but cannot find my error. The issue is that after login the chat window re-displays the same info over and over (the last few entries), scrolling down to infinity. Any hints or suggestions would be appreciated, otherwise this tutorial was great, despite what nobody says. :-)
January 23rd, 2006 at 8:20 pm
the problem is the mysql.php file. at the end of the file, there is a blank (whitespace) after the php end tag ?>
this causes the chatserver to return a blank as first character. so the the timestamp is always in the past and the messages are re-displayed.
step of my solutionfinding:
1.) call chatserver.php and have a look what it really delivers (not in the browser, in the source.
2.) add a header(”Content-type: text/plain”); before the response in function send_messages() before die($response);
3.) the error shows you the position, why the header can not be sent. (mysql.php:229)
thats all folks
pmcweb.at
January 24th, 2006 at 8:23 pm
Hi,
I have the same problem of Todd, The last entrie is repeated to infinity.
If someone can help me.
Thx
January 28th, 2006 at 10:36 pm
Hi,
the problem are found by pmcweb.at, I have just change this :
// We’re getting a valid response, first get the latest timestamp
latest = response.substring(1,11);
// Now get the messages
var messages = response.substring(11, response.length);
Do you notice that chat doesn’t work very well with Internet Explorer ?
Yen
February 2nd, 2006 at 9:10 pm
WOW!! Nice tutorial to explain the power of ajax. My respect to you, there should be more people like you.
I fixed the “undefined”-bug like this (script.js @ line 97)
// Add each message
var chat = $(’chat’);
for (var i=0; i “);
if(message == ‘undefined’ || message == ‘’ || message == null) continue;
chat.value = chat.value + ‘\n’;
chat.value = chat.value + message[0] + ‘: ‘ + message[1];
}
It fixes for me.
February 2nd, 2006 at 9:12 pm
Huh?? Your script cut my code into pieces of s…
Ok, line 84 I add a validation of message, its inside the for(i
February 9th, 2006 at 5:43 pm
Hi,
I have the same problem like Yen, but i have another solution.
I’ve seen that there is a white-space in the first position of the return of Ajax in the function “handle_response”…
so, if i apply the function “trim” to the response, it will works, and i don’t have to change the code like Yen.
Sorry for my english but i’m french.
thanks a lot
Matthieu
March 6th, 2006 at 6:00 am
yeh there are some bugs. i left it a little while and then something i typed came up in duplicate, then this came up. need some better error checking.
HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”:
March 16th, 2006 at 1:40 pm
Yeah, this is a very gud script i’ve come across. Dont care about nobody. NOBODY is a shit creature in this world. Is this script working fine with u all. I haven’t checked yet. Got impressed with this n replied right back.
March 21st, 2006 at 7:06 pm
Thanks for the great lesson. I’m just starting to do some server administration, setting up php and mysql, and I found this a great way to A) test my installations and B) get to know basic php and mysql and the basics of AJAX techniques. Thanks a lot and I hope the second edition of this tutorial comes out soon!
April 4th, 2006 at 2:46 am
[…] Tra le moltissime letture, mi ero dimenticato di far presente del primo di una serie di articoli dedicati alla creazione di una chat utilizzando il linguaggio di programmazione PHP ed ovviamente Ajax. Be’, lo faccio ora insieme all’annuncio dell’uscita della seconda parte. […]
April 7th, 2006 at 10:27 pm
Matthieu, where exactly did you invoke the trim() function. I’ve toyed with it all over the place, and either NO text shows up, or I keep getting the error…
April 11th, 2006 at 4:08 pm
Very good chat, in addition the code is very easy to understand, speaks and writes in Spanish, reason why I use carácteres special in my writing, which does not accept. Felecitaciones to the developer of this application, that is very useful for the people who we are beginning in this technique of development Web (Ajax).
April 25th, 2006 at 10:32 pm
[…] April 26, 2006 at 4:15 am · Filed under PHP, 文献翻译 完整显示 1 2 3 4 5 原文地址 作者:Dennis Pallett 译者:!oEL […]
April 25th, 2006 at 10:34 pm
lol, just finished translating part 1 into chinese and posted on my blog (of course i saved your original info. what am i, a pirate? no seriously, if you have any problem with this, i’ll stop, or i’ll continue translating your goodies :)
June 17th, 2006 at 4:21 am
There is a way to slove this problem:
add this function in script.js:
String.prototype.trim = function()
{
return this.replace(/(^\s+)|\s+$/g,”");
}
and then change : var response = request.responseText;
use:var response = request.responseText.trim(); it will work;
sorry about my english