Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

- - - - -

Simple Chatroom with PHP & jQuery

ajax jquery

  • This topic is locked This topic is locked
16 replies to this topic

#1 Guest_Jaan_*

Guest_Jaan_*
  • Guest

Posted 11 August 2009 - 04:41 AM

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:

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

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


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


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


// 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", {

text: message

});

// 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",
cache: false,
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({ scrollTop: newheight }, '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",
cache: false

});

}

// 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_messages, 500);
setInterval(load_users, 5000);

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

index.php


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


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

Posted Image

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

I hope you liked it..

Edited by Alexander, 21 June 2011 - 09:40 PM.
bb tags

  • 0

#2 Guest_Jordan_*

Guest_Jordan_*
  • Guest

Posted 11 August 2009 - 04:51 AM

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

#3 Guest_Jaan_*

Guest_Jaan_*
  • Guest

Posted 11 August 2009 - 06:08 AM

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

#4 WingedPanther73

WingedPanther73

    A spammer's worst nightmare

  • Moderator
  • 17757 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others

Posted 11 August 2009 - 07:34 AM

Very cool :)
  • -1

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

My MineCraft server site: http://banishedwings.enjin.com/


#5 Guest_Jaan_*

Guest_Jaan_*
  • Guest

Posted 12 August 2009 - 01:56 AM

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 ^^
  • 0

#6 Guest_Jordan_*

Guest_Jordan_*
  • Guest

Posted 12 August 2009 - 04:29 AM

Does it still use to many system resources?
  • 0

#7 John

John

    CC Mentor

  • Moderator
  • 4450 posts
  • Location:New York, NY

Posted 12 August 2009 - 06:30 AM

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.
  • 0

#8 Guest_Jaan_*

Guest_Jaan_*
  • Guest

Posted 12 August 2009 - 01:59 PM

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

#9 John

John

    CC Mentor

  • Moderator
  • 4450 posts
  • Location:New York, NY

Posted 12 August 2009 - 02:54 PM

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.

$sql = "SELECT time,user,text FROM chat ORDER BY time DESC LIMIT 50";

  • 0

#10 Guest_Jordan_*

Guest_Jordan_*
  • Guest

Posted 12 August 2009 - 02:59 PM

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

#11 John

John

    CC Mentor

  • Moderator
  • 4450 posts
  • Location:New York, NY

Posted 12 August 2009 - 03:17 PM

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


I didn't actually look at the table structure - I had assumed there was an id column for a primary key. I think the help comes from limiting the output.
  • 0

#12 Guest_Jordan_*

Guest_Jordan_*
  • Guest

Posted 12 August 2009 - 03:42 PM

I didn't even notice that:

$sql = "SELECT * FROM chat";

Yeah, I see no reason to load every chat ever submitted.
  • 0





Also tagged with one or more of these keywords: ajax, jquery

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download