ASPit - Totally ASP JSit - Totally JavaScript
Search PHPit

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

Advertisements

Creating a chat script with PHP and Ajax, Part 2

(Page 5 out of 5)

Sending chat messages

To send a new message, a function called 'send_message()' is used, and this function sends the message to the chat server, using an Ajax request, like so:

function send_message() {
        var talk = $('talk');
        var msg = talk.value;

        if (msg == '') {
                return false;
        }

        // Send message
        var url = base_url + 'chat.php';
        var pars = creds() + '&message=' + escape(msg);

        var ajax = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete: handle_ping});

        Logger.info("Sent message: " + pars);

        // Clear field
        talk.value = '';
}

The function first gets the value of the message field, and makes sure it isn't empty. After that it sends the message, and the user's credentials, to the chat.php file, using an Ajax request.

The chat.php file only does two things: checks the user credentials and adds the new message. Checking the user credentials is extremely easy, as we've already got a function for that: auth_user() (see the previous section).

If the user credentials are okay, the chat.php file then uses the add_message() function to add a message, and this function looks like this:

function add_message ($user) {
        global $db;

        // Get vars
        $message = r('message');
        $username = $user['username'];
        $time = time();
        $token = generate_password(5);

        if (empty($message)) { return false; }

        // Insert message
        $ok = $db->execute ("INSERT INTO message (username, time, message, token) VALUES (?, ?, ?, ?)", array($username, $time, $message, $token));

        // All done
        return true;
}

It's pretty much a basic database insert, and there's nothing spectacular about it. Note how we generate a random token, to prevent the duplicate message problem, which I talked about in the previous section.

That's it!

I've taken you pretty much through everything in the Ajax/PHP chat, and I've shown you the most important parts.

It's very understandable if you had a hard time following this article, as "the glue" between all the parts is still pretty much missing. That's why you can click here to download the complete Ajax/PHP chat.

Make sure to open includes/global.php and change your MySQL details, so that they are correct. Also make sure you've already created the database, and setup the right structure.

If you want to give the chat a test run, click here to view a live demo right here on PHPit.net.

In the next part of this article series, we'll add some more features and improve our chat by making it more stable. Some of the new things we'll be adding are registered users, administrators, and a silenced chat room.

If you have any questions or comments, feel free to leave them below, or join us at PHPit Forums.

« Previous: Ping? Pong!



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

  1. AjaxBlog.it » 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. www.stuffvideo.com » Ajax article Says:

    […] http://phpit.net/article/ajax-php-chat-part-two/1/ […]

  7. Michael Says:

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

  8. Prasanna Says:

    Hi

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

    Will download the code to dwell deep into it.

    Thanks
    Prasanna

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
PDF
Download this article as a PDF file