ASPit - Totally ASP JSit - Totally JavaScript
Search PHPit

Use this textbox to search for articles on PHPit. Seperate keywords with a space.


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:

function login() {
        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});"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

// 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


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:

function login_handle_response(request) {
        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') {
                return false;

        // Which action?
        if (data.action == 'login' && data.success == true)     {

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:

function do_login(data) {
        // 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

        // Show chat
        var el = $('chat'); = '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:

function add_userlist(list) {
        var ul_users = $('users');
        ul_users.innerHTML = '';

        list.each( function(user) {
                var new_li = document.createElement('LI');
       = 'user-' + user.userid;
                new_li.innerHTML = user.username;


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.

« Previous: Basic Necessities & Chat Client
Next: Ping? Pong! »

8 Responses to “Creating a chat script with PHP and Ajax, Part 2”

  1. » Creare una chat con PHP ed Ajax Says:

    […] 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. […]

  2. Matthijs Says:

    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?

  3. Bernhard Froehlich Says:

    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.

  4. berhard kuisper Says:

    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

  5. Aaron Hancock Says:

    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.

  6. » Ajax article Says:

    […] […]

  7. Michael Says:

    There are some Problems with UTF-8 with German Umlaute (ä ü ö). How can i handle this?

  8. Prasanna Says:


    This is a gr8!!!!!!!!!! article…

    Will download the code to dwell deep into it.


Leave a Reply

About the author
Dennis Pallett is the main contributor to PHPit. He owns several websites, including ASPit and Chill2Music. He is currently still studying.
Article Index
  1. Introduction & Structure
  2. Basic Necessities & Chat Client
  3. Creating the login
  4. Ping? Pong!
  5. Sending new messages
Bookmark Article
Download Article
Download this article as a PDF file