Creating a chat script with PHP and Ajax, Part 2
(Page 3 out of 5)Creating the login
If you have a look at the HTML in the previous example, you will notice that the login link uses a function called 'login()'. This function has to send the username that was filled in by the visitor to the server, using an Ajax request.
It looks like this:
var username = $F('username');
// Check if username isn't empty
if (username == '') {
alert('Please enter a username');
return false;
}
// Send login request
var url = base_url + 'login.php';
var pars = 'username=' + escape(username);
var ajax = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete: login_handle_response});
Logger.info("Logged in: " + pars);
}
The function makes sure a username was filled in, and then sends the request to 'login.php'. For easy debugging it also logs the information using the Logger library.
On the server side, PHP has to handle this request, and return the appropriate response. What the login.php file has to do is make sure that username isn't already in use by someone else, then insert the new user, and finally return the user list. It looks like this:
include ('includes/global.php');
// Get username and generate last active and random password
$username = r('username');
$lastactive = time();
$password = generate_password(15);
// No username?
if (empty($username) == true) {
return_error('Please fill in a username', 10);
}
// Make it safe
$username = htmlentities($username);
// Remove any inactive users
remove_inactive_users();
// Try to insert new user
$ok = $db->execute ("INSERT INTO `user` (username, lastactive, password) VALUES (?, ?, ?)", array($username, $lastactive, $password));
// Unique error? (errorno = 1062)
if ($db->ErrorNo() == 1062) {
return_error ('Another user is already using this username. Please pick another one.', 20);
}
// Return success, by sending the complete userlist
$return = array('success' => true, 'action' => 'login', 'username' => $username, 'lastactive' => $lastactive, 'password' => $password);
// Get userlist
$userlist = $db->GetAll("SELECT userid, username FROM `user`");
$return['userlist'] = $userlist;
// Return JSON
return_raw_json($return);
?>
Most of the above is fairly self-explanatory, and should be easy to understand. Please note that the remove_inactive_users() function is used to remove any inactive users, and can be found in the user-functions.php file, which can be downloaded by clicking here, and should be stored in the includes directory.
At the end of the example above the return_raw_json() function is used to return the user list to the chat client. This function can be found in the common functions.php file, and uses the PHP-JSON library to send the JSON.
Now that login.php has sent a response, the chat client has to handle this. When sending the original request, we actually defined a feedback handler called login_handle_response, which looks like this:
var data = request.responseText;
// Transform JSON
data = JSON.parse(data);
if (data == false) {
// Not JSON
alert('An unexpected error happened. Please try again');
return false;
}
if (typeof(data.error) != 'undefined') {
alert(data.error.msg);
return false;
}
// Which action?
if (data.action == 'login' && data.success == true) {
do_login(data);
}
}
This is just a really basic function to transform the returned JSON into a native JS object, and then calls the do_login() function to continue the login process.
The do_login() function takes in the data returned by login.php, shows the chat, and creates the user list. It looks like this:
// Are password and lastactive there?
if (typeof(data.lastactive) == 'undefined' || typeof(data.password) == 'undefined') {
alert('An unexpected error happened. Please try again');
return false;
}
// Save them
password = data.password;
lastactive = data.lastactive;
username = data.username;
// Insert users into userlist
add_userlist(data.userlist);
// Show chat
Element.hide('login');
var el = $('chat');
el.style.display = 'block';
var ping_obj = new PeriodicalExecuter(ping, 1);
}
A very important thing which the do_login() function does is creating a new 'PeriodicalExecuter' object, which is the whole core behind our chat. It's basically a timer that runs the ping() function every second, and that's the function which gets the new messages in.
The do_login() function also uses the add_userlist function, which is used to create the user list and looks like this:
var ul_users = $('users');
ul_users.innerHTML = '';
list.each( function(user) {
var new_li = document.createElement('LI');
new_li.id = 'user-' + user.userid;
new_li.innerHTML = user.username;
ul_users.appendChild(new_li);
});
}
That's pretty much it for the login part, and all we need to write now is the code necessary to get new messages and any changes in the userlist.
April 4th, 2006 at 2:47 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 4th, 2006 at 5:46 pm
Very interesting article. Will certainly download the code and study it some more. Thanks.
One question though: how is the escaping of the data to the db handled? I didn’t study all code yet, but in your article in the login script there’s only the code
// Make it safe
$username = htmlentities($username);
before the data is sent to the db.
Does ADODB handle the escaping itself?
April 5th, 2006 at 12:24 pm
It’s a good example for what can be done with Ajax but it’s no real world example. Webchats are supposed to serve at least 1000 Clients but this thing will kill the Server if there are more than ~100 and i testet the live demo - it’s having a lag of about 2sec and thats not good in real world.
But nevertheless a nice example.
April 9th, 2006 at 2:56 am
Its realy good chat but this is php. I code java chats and i have mor than 2000 users in this system , but with php server was slow or down.
Sorry java is greater for chatsystems or php for a alternativ session!
Best regards
April 18th, 2006 at 4:15 pm
Bernhard, I think the delay is due to the refresh/reload rate and not server lag. With a few tweaks, this would make a great small scale chat client.
April 24th, 2006 at 7:26 pm
[…] http://phpit.net/article/ajax-php-chat-part-two/1/ […]
June 28th, 2006 at 1:57 am
There are some Problems with UTF-8 with German Umlaute (ä ü ö). How can i handle this?
August 7th, 2006 at 11:52 am
Hi
This is a gr8!!!!!!!!!! article…
Will download the code to dwell deep into it.
Thanks
Prasanna