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 1

(Page 3 out of 4)

Creating the client

You can close your PHP editor now, and switch to your HTML/JS editor, as we'll only be using HTML and JavaScript from now on.

First of all, the client page itself. It's nothing advanced, and very simple:


       
                </span>Ajax Chat Client<span class="sc2"><span class="kw2">

                type="text/javascript" src="../prototype.js">
                type="text/javascript" src="script.js">

                REL="stylesheet" HREF="../style.css" TYPE="text/css" media="all">

       

        id="container">
               

Ajax Chat Client

                id="login">
                       

Please enter an username:


                        type="text" name="user" id="user" />
                        type="button" onclick="login();" value="Enter Chatroom" />
               

                id="chatelements" style="display:none;">
                        id="chat" rows="20">
                        type="text" id="message"> type="button" onclick="send_message();" value="Send" />
               


               
                id="debug">
               

                id="copyright">
                        This is a demo of an article series on href="http://phpit.net">PHPit.
                        Copyright © 2006 Dennis Pallett.
               


       

It has three important elements: the login div, which shows a login box when first viewing the page, a textarea, which is used to show all the chat messages, and a text field which is used to enter new messages.

The page also includes three external files: prototype.js (the Prototype library), script.js (our custom chat functions) and style.css, which is just a stylesheet file and can be downloaded here: style.css.

If you have a close look at the HTML above, you'll notice two different JS functions: login() and send_message(). These are defined in the script.js file, and are the most important of our chat script.

The login() function is used to set a user's username, and getting the initial messages. It looks like this:

var server = 'http://projects/phpit/content/creating%20an%20ajax-based%20chat/demos/1/chatserver.php';

var username = '';
var latest = '';
function login() {
        // Get username
        var user = $F('user');

        if (user == '') {
                alert('Please enter a username before entering the chat room');
                return false;
        }

        username = user;

        // Show chat
        Element.hide('login');
        Element.show('chatelements');

        $('chat').value = '';
        $('message').value = '';

        // Begin getting messages
        get_messages();
        checker = new PeriodicalExecuter(get_messages, 2);
}

The first part of the function checks the username. If everything is okay, the chat elements are shown, and the latest messages are retrieved using the get_messages() function. The function also creates a new object, called the PeriodicalExecuter, which is used to check for new messages every 2 seconds.

The get_messages() function is used to retrieve new functions using an Ajax request, like so:

function get_messages() {
        var args = 'action=get&latest=' + latest;
        var do_ajax = new Ajax.Request(server, {method: 'get', parameters: args, onComplete: handle_response});
}

The above code uses the Ajax object (included with the Prototype library) to send a new GET request to the server with two arguments: action and the timestamp of the latest message received. As you can see, the onComplete parameter has been set to handle_response, which means that when the Ajax request is done, the response will be sent to a function called handle_response().

The handle_response() function actually checks the response, and decides what to do. Remember the responses that we gave in the server? We're going to use that now, like so:

function handle_response(request) {
        var response = request.responseText;

        // Error?
        if (response == 'error:no-user') {
                // No username, show login again
                alert('It appears you aren\'t logged in any longer. Please login again');
                Element.show('login');
                Element.hide('chatelements');
                return false;
        }
        if (response == 'error:no-message') {
                // No username, show login again
                alert('You didn\'t send any message. Please try again');
                return false;
        }
        if (response == 'no-messages'){
                // There are no new messages
                return false;
        }

        // We're getting a valid response, first get the latest timestamp
        latest = response.substring(0, 10);

        // Now get the messages
        messages = response.substring(10, response.length);

        // Split messages
        messages = messages.split('\n');

        // Add each message
        var chat = $('chat');
        for (var i=0; i < messages.length; i++) {
                var message = messages[i].split(">");
               
                chat.value = chat.value + '\n';
                chat.value = chat.value + message[0] + ': ' + message[1];
        }
}

This function first checks whether any errors have been returned. This only happens when a message has been sent (and not when receiving messages). After that it checks whether there are any messages.

If there are new messages, it parses the new messages (using some standard string functions), and then adds the new messages to the chat area.

And that's all there is to it. We've now got an almost working chat script. All that's left is to write the send_message() function.

« Previous: Creating the server
Next: Conclusion »



This article was posted on Monday, January 2nd, 2006 at 5:26 pm. You can follow any responses to this article through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

19 Responses to “Creating a chat script with PHP and Ajax, Part 1”

  1. nobody Says:

    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.

  2. Dennis Pallett Says:

    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.

  3. Will Says:

    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.

  4. Todd Says:

    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. :-)

  5. pmcweb.at Says:

    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

  6. Sw3eT Says:

    Hi,
    I have the same problem of Todd, The last entrie is repeated to infinity.
    If someone can help me.
    Thx

  7. Yen Says:

    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

  8. Mike Greubel Says:

    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.

  9. Mike Greubel Says:

    Huh?? Your script cut my code into pieces of s…

    Ok, line 84 I add a validation of message, its inside the for(i

  10. Matthieu Says:

    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

  11. spadgos Says:

    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”:

  12. Rock Says:

    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.

  13. nickp Says:

    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!

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

  15. Cypheros Says:

    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…

  16. Jorge Rubiano Says:

    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).

  17. :v:revolution - web:v:]中文[: » 用PHP和Ajax技术构建实时聊天系统(一) Says:

    […] April 26, 2006 at 4:15 am · Filed under PHP, 文献翻译 完整显示   1 2 3 4 5 原文地址 作者:Dennis Pallett 译者:!oEL […]

  18. WoOzY Says:

    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 :)

  19. xilin Says:

    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

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 & How it works
  2. Creating the server
  3. Creating the client
  4. Conclusion
Bookmark Article
Download Article
PDF
Download this article as a PDF file