Closed Thread
Page 1 of 2 12 LastLast
Results 1 to 10 of 17

Thread: Simple Chatroom with PHP & jQuery

  1. #1
    Jaan Guest

    Simple Chatroom with PHP & jQuery

    Hey there.. few days ago I got bored, I was talking with some girls in msn.. ya know that sleek talk and suddenly this idea came to my head that I should make a jQuery chat.. And I did it, Sugar Chat 1.0 this is little complicated version of this tutorial but I show it as a demo..

    So let's start..

    First let's make a database and create tables:

    Code:
    CREATE TABLE IF NOT EXISTS `auth` (
    `user` varchar(30) NOT NULL,
    `session` varchar(50) NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    
    
    CREATE TABLE IF NOT EXISTS `chat` (
    `time` varchar(30) NOT NULL,
    `user` varchar(30) NOT NULL,
    `text` text NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    Let's add some style to our chatroom with this:

    style.css

    Code:
    body{
    
    font-family: Verdana;
    font-size: 11px;
    background-color: #BFC08D;
    
    }
    
    .tablebottom{
    
    border-bottom: 1px solid #E6E6E6;
    
    }
    
    .middlebox{
    
    border-bottom: 1px solid #E6E6E6;
    border-left: 1px solid #E6E6E6;
    
    }
    
    #maintable{
    
    border: 1px solid #E6E6E6;
    background-color: #C9CCBB;
    
    }
    
    #chatscreen{
    
    width: 850px;
    height: 500px;
    float: left;
    overflow: auto;
    text-align: left;
    
    }
    
    #onlineusers{
    
    height: 500px;
    width: 100px;
    float: right;
    
    }
    
    a{
    
    text-decoration: none;
    color: #000000;
    
    }
    
    a:hover{
    
    text-decoration: none;
    color: #8DBAEB;
    
    }
    
    input{
    
    border: 1px solid #E6E6E6;
    
    }
    
    #submitbutton{
    
    background-color: #FFFFFF;
    font-family: Tahoma;
    
    }
    
    #messagebox{
    
    background-color: #E8E9E2;
    
    }
    
    #userbox{
    
    background-color: #E8E9E2;    
    height: 20px;
    
    }
    
    #usersbox{
    
    text-align: left;
    background-color: #E8E9E2;    
    
    }
    
    .user{
    
    border-bottom: 1px solid #969A7A;
    
    }
    Now when it's done let's create our config file..

    config.php

    Code:
    <?php

    // Let's connect to our database
    // Usually your host is 'localhost'
    // But sometimes it might be different so ask your host
    // About your database server address
    $mysql_con mysql_connect("localhost""Username""Password");

    // Now let's check if everything is good
    // If there's something wrong.. let's display an error
    if(!$mysql_con){

    die(
    mysql_error());

    }

    // Let's select our database
    $mysql_db mysql_select_db("DatabaseName"$mysql_con);

    // Let's check here also is everything is okay
    // If there's something wrong, let's display an error
    if(!$mysql_con){

    die(
    mysql_error());

    }

    ?>
    Now our config file is ready, database has been set up and now are we ready to start creating our chat

    First we need to download jQuery libary. You can find it here.

    Let's create an "includes" folder and let's put it there.

    Now let's create our functions file that will put everything to work..

    actions.php

    Code:
    <?php

    // Let's start our session
    session_start();

    // Include the config.php because we are
    // Going to start work with our database
    include("config.php");

    // First let's make a login form
    // Here user sets his/her username that
    // He/she will use in this chatroom
    function login_form(){

    echo 
    "<br /><br />";
    echo 
    "<table width='500' border='0' id='maintable' style='background-color: #F3F3F3' align='center'>"
    ."<tr>"
    ."<td align='center'><font style='font-size: 20px'>Login</font></td>"
    ."</tr>"
    ."<tr>"
    ."<td align='center'>";
    echo 
    "<form action='index.php?act=login' method='post'>"
    ."Username: <input type='text' name='username' /> <input type='submit' id='button' value='Login' /><br /><br />"
    ."</form>";    
    echo 
    "</td>"
    ."</tr>"
    ."</table>";

    }

    // Now let's log that user in
    function process_login(){

    // Let's get user's username
    $username $_REQUEST['username'];

    // Now let's find if there are records about him/her in database
    $sql "SELECT * FROM auth WHERE user='".mysql_real_escape_string($username)."'";
    $query mysql_query($sql);

    // If there are any records, delete them
    if(mysql_num_rows($query)>0){

    $sql "DELETE FROM auth WHERE user='".mysql_real_escape_string($username)."'";
    $query mysql_query($sql);

    // Check that everything is okay
    // If something is wrong, display an error
    if(!$query){

    die(
    mysql_error());

    }

    }

    // Now let's set session with user's name
    // And insert it into database so we know that
    // He/she is logged in
    $_SESSION['user'] = $username;
    $sql "INSERT INTO auth (user, session) VALUES ('".mysql_real_escape_string($username)."', '".session_id()."')";
    $query mysql_query($sql);

    // Check that all things went well
    // If something was wrong, display an error
    // But if evetrything is good, redirect him/her 
    // To the chatroom
    if(!$query){

    echo 
    "Can not insert info into database!<br />"mysql_error();

    }else{

    header("Location: index.php");

    }

    }

    // Now let's make a function that logs users our
    function logout(){

    // This will delete any traces of him/her
    // From database so it will be a clean sheet
    // When he/she comes back
    $sql "DELETE FROM auth WHERE session='".mysql_real_escape_string(session_id()). "'";
    $query mysql_query($sql);

    // Little error checking again
    if(!$query){

    echo 
    "Can not delete info from database!";

    }else{

    // If everything went well, let's destroy
    // Session and redirect to main page also
    // Where login form waits him/her
    session_destroy();
    header("Location: index.php");

    }

    }

    // Now we want to show user's username
    // In "Welcome [user]" area
    function get_username(){

    // Let's get all info abour our current session from database
    $sql "SELECT * FROM auth WHERE session='".mysql_real_escape_string(session_id()). "'";
    $query mysql_query($sql);
    $row mysql_fetch_array($query);

    // If there aren't any records
    // Let's set our user's name to "Guest"
    // If there are records let's get the real username
    if(mysql_num_rows($query) == "0"){

    $username "Guest";

    }else{

    $username $row['user'];

    }

    return 
    $username;

    }

    // Now we want to display "Log In" or "Log Out"
    // Link after greeting
    function get_link(){

    // Again we check for records from database
    $sql "SELECT * FROM auth WHERE session='".mysql_real_escape_string(session_id()). "'";
    $query mysql_query($sql);
    $row mysql_fetch_array($query);

    // If there are no records about our user
    // Let's display "Log In" link
    // But if there are records about our user
    // Display a "Log Out" link
    if(mysql_num_rows($query) == "0"){

    $link "<a href='index.php?act=login'>Log In</a>";

    }else{

    $link "<a href='index.php?act=logout'>Log out</a>";

    }

    return 
    $link;    

    }

    // This is the function that posts
    // User messages to database
    function post_message(){

    // Let's clean our text that user entered
    $text addslashes(htmlentities(htmlspecialchars($_REQUEST['text'])));

    // Now let's insert it into database
    $sql "INSERT INTO chat (time, user, text) VALUES ('".date("H:i")."', '".get_username()."', '".$text."')";
    $query mysql_query($sql);

    // Little error checking and we are done
    if(!$query){

    die(
    mysql_error());

    }

    }

    // Now we have to get messages
    // From database to see what other users are writing
    function get_messages(){

    // Now let's get all info from "chat" table
    $sql "SELECT * FROM chat";
    $query mysql_query($sql);

    // Some error checking
    if(!$query){

    echo 
    "Can not get messages from database.";

    }else{

    // If everything is fine let's display our messages
    // First to come is time, it will look like this (12:34)
    // Second is user's name and after that comes the text
    // For example: (13:54) Jaan: Hey there!
    while($row mysql_fetch_array($query)){

    echo 
    "(".$row[time].") "."<b>".$row['user'].":</b> ".$row['text']."<br />";

    }

    }    

    }

    // Now let's get users that are using this
    // Chatroom, so people can see who they are talking
    function get_users(){

    // Let's get all info from "auth" table
    $sql "SELECT * FROM auth";
    $query mysql_query($sql);

    // Check that everything is fine
    if(!$query){

    echo 
    "Can not get users from database.";

    }else{

    // If everything is fine, let's display all users
    while($row mysql_fetch_array($query)){

    echo 
    "<div class='user'>".$row['user']."</div>";

    }

    }

    }

    // Here's the engine that puts everything to work
    // All functions are triggered when they are wanted
    // For example we want to log our user out
    // We put this link to our page: <a href='index.php?act=logout'>Log out</a>
    // And as you see when "act" isn't empty and "act" is "logout"
    // Let's trigger logout() function that logs our user out
    // Everything works the same with other functions

    $act addslashes(htmlentities(htmlspecialchars($_GET['act'])));

    if(
    $act != "" && $act == "logout"){

    logout();

    }elseif(
    $act != "" && $act == "login"){

    process_login();

    }elseif(
    $act != "" && $act == "post"){

    post_message();

    }elseif(
    $act != "" && $act == "getmessages"){

    get_messages();
    exit;

    }elseif(
    $act != "" && $act == "getusers"){

    get_users();
    exit;

    }

    ?>
    Now when this is done.. let's create our jQuery page that will make everything dynamical and you don't have to refresh page..

    process.js

    Code:
    // If page is loaded let's load our functions
    $(function(){

    // If submit button has been clicked
    $("#submitbutton").click(function(){

    // Let's get what user has entered to the text field
    var message = $("#text").val();

    // Now let's post this text
    $.post("includes/actions.php?act=post", {

    textmessage

    });

    // When user's text is posted
    // Remove it from the text field    
    $("#text").attr("value""");

    return 
    false;

    });

    // Now let's load our messages
    function load_messages(){

    // Let's use AJAX to get them from our actions file
    $.ajax({

    url"includes/actions.php?act=getmessages",
    cachefalse,
    success: function(html){

    // Let's get old posts from there
    // Where user's posts are shown
    $("#chatscreen").html(html); 

    // Now let's get this area's height where
    // All posts are displayed and then let's animate
    // It little bit so the scrollbar is always 
    // Scrolled down so you can see the new posts    
    var newheight = $("#chatscreen").attr("scrollHeight") - 20;

    $(
    "#chatscreen").animate({ scrollTopnewheight }, 'fast'); 

    },

    });

    }

    // Now let's load chatroom's active users    
    function load_users(){

    // Let's use AJAX also to get chatroom's users
    $.ajax({

    url"includes/actions.php?act=getusers",
    cachefalse    

    });

    }

    // Now let's set the time when we will
    // Check for new messages and new users
    // First, we set the time of our posts
    // setInterval(load_messages, 500) loads our posts every 0.5 seconds
    // setInterval(load_users, 5000) loads our posts every 5 seconds
    setInterval(load_messages500);
    setInterval(load_users5000);    

    }); 
    Now everything is almost done.. we need a index file so let's build it..

    index.php

    Code:
    <?php

    // Let's start session and let's include our files
    session_start();
    include(
    "includes/config.php");    
    include(
    "includes/actions.php");

    ?>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

    <head>
    <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
    <title>Sugar Chat 1.0</title>
    <script src="includes/jquery.js" type="text/javascript"></script>
    <script src="includes/process.js" type="text/javascript"></script>
    <link href="includes/style.css" rel="stylesheet" type="text/css" />
    </head>

    <body>

    <?php

    // Now if our username is "Guest"
    // Let's display the login form
    if(get_username() == "Guest"){

    echo 
    "<td>"
    .login_form()
    .
    "</td>";

    // If it isn't let's display the chatroom    
    }else{

    ?>

    <table width="900" border="0" align="center" id="maintable">
    <tr>
    <td class="tablebottom" colspan="2" id="userbox">
    <?php 

    // Let's say greetings to the user and display the "Log out link"
    echo "Welcome: ".get_username()."! (".get_link().")"

    ?>
    </td>
    </tr>
    <tr>
    <td align="center" class="tablebottom">
    <div id="chatscreen">

    <?php

    // Now here is the same thing that is in actions file
    // Let's select all info from "chat" table
    $sql "SELECT * FROM chat";
    $query mysql_query($sql);

    // Little error checking again
    if(!$query){

    echo 
    "Can not get messages from database.";

    }else{

    // If everything is good let's display
    // User's messages
    while($row mysql_fetch_array($query)){

    echo 
    "<div align='left'>(".$row[time].") "."<b>".$row['user'].":</b> ".$row['text']."</div>";

    }

    }    

    ?>

    </div>
    </td>
    <td class="middlebox" id="usersbox" rowspan="2">
    <div id="onlineusers">

    <?php

    // This is also like in actions file
    // Get all info from "auth" table
    $sql "SELECT * FROM auth";
    $query mysql_query($sql);

    // Check for errors
    if(!$query){

    echo 
    "Can not get users from database. ".mysql_error();

    }else{

    // If everything is fine
    // Let's display active users
    while($row mysql_fetch_array($query)){

    echo 
    "<div class='user'>".$row['user']."</div>";

    }

    }

    ?>

    </div>
    </td>
    </tr>

    <tr>
    <td colspan="2" id="messagebox">
    <form action="">
    <input type="text" size="129" id="text" name="chattxt" /> <input type="submit" id="submitbutton" value="Send" /> 
    </form>
    </td>
    </tr>
    </table>

    <?php

    }

    ?>

    </body>
    </html>
    As you can see it from here:

    HTML Code:
    <script src="includes/jquery.js" type="text/javascript"></script>
    <script src="includes/process.js" type="text/javascript"></script>
    <link href="includes/style.css" rel="stylesheet" type="text/css" />
    I have put all files that we created before into "includes" folder.. So it looks cleaner

    Anyway the login form looks like this:



    This and other things you can try out in demo..

    I hope you liked it..
    Last edited by Alexander; 06-21-2011 at 10:40 PM. Reason: bb tags

  2. CODECALL Circuit advertisement

     
  3. #2
    Jordan Guest

    Re: Simple Chatroom with PHP & jQuery

    The end result sure does look a lot more complicated than you make it appear above. Nice tutorial and nice work! +rep

  4. #3
    Jaan Guest

    Re: Simple Chatroom with PHP & jQuery

    Hehe yes I know it looks complicated but it's really very simple..
    and thank you

  5. #4
    Join Date
    Jul 2006
    Posts
    16,478
    Blog Entries
    75
    Rep Power
    143

    Re: Simple Chatroom with PHP & jQuery

    Very cool
    Programming is a branch of mathematics.
    My CodeCall Blog | My Personal Blog

  6. #5
    Jaan Guest

    Re: Simple Chatroom with PHP & jQuery

    Yea.. I'm working on it atm.. I believe it will be my next project.. I just wanted to post it here so you can do something cool also

  7. #6
    Jordan Guest

    Re: Simple Chatroom with PHP & jQuery

    Does it still use to many system resources?

  8. #7
    Join Date
    Jul 2006
    Location
    Amherst, New York, United States
    Posts
    6,277
    Blog Entries
    26
    Rep Power
    20

    Re: Simple Chatroom with PHP & jQuery

    Quote Originally Posted by Jordan View Post
    Does it still use to many system resources?
    He is selecting ALL the entries from the chat table, so I'd assume once the table reaches ten thousand+ entries, it would probably be enough to kill the mysql server.

  9. #8
    Jaan Guest

    Re: Simple Chatroom with PHP & jQuery

    Yes.. that's why i made a deletion script that deletes some of posts..like.. in every 100 posts it deletes 50

  10. #9
    Join Date
    Jul 2006
    Location
    Amherst, New York, United States
    Posts
    6,277
    Blog Entries
    26
    Rep Power
    20

    Re: Simple Chatroom with PHP & jQuery

    I *think* if you limit the output in the query, it won't cause such a large load if you have a large data set, this way you will be able to keep chat logs.

    Code:
    $sql "SELECT time,user,text FROM chat ORDER BY time DESC LIMIT 50"

  11. #10
    Jordan Guest

    Re: Simple Chatroom with PHP & jQuery

    lol, how does that help? You just listed every field in the chat table. Select * is effectively the same with less typing.

Closed Thread
Page 1 of 2 12 LastLast

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Replies: 1
    Last Post: 10-13-2011, 08:52 PM
  2. Replies: 0
    Last Post: 06-22-2011, 09:57 PM
  3. Jquery help
    By ahmed in forum JavaScript and CSS
    Replies: 1
    Last Post: 06-12-2011, 11:48 AM
  4. Replies: 1
    Last Post: 04-22-2011, 11:18 AM
  5. PHP / Jquery Help
    By tridiantgames in forum PHP Development
    Replies: 2
    Last Post: 08-31-2010, 09:40 PM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts