I received lot of email requests from my reader that asked to me how to develop a facebook lite chat application. In this post I'm just giving an idea about chat application with simple javascript. I had implemented this at clouds.9lessons.info

Download Script
Live DemoDatabase
CREATE TABLE chat
(
id INT PRIMARY KEY AUTO_INCREMENT,
user VARCHAR(50) UNIQUE,
msg VARCHAR(200),
);
(
id INT PRIMARY KEY AUTO_INCREMENT,
user VARCHAR(50) UNIQUE,
msg VARCHAR(200),
);
chat.php
Contains PHP, Javascript and HTML code. Run this file with chat.php?user=yourname
<?php
include('db.php');
if($_GET['user'])
{
$user=$_GET['user'];
?>
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
var user='<?php echo $user;?>';
// Requesting to Database every 2 seconds
var auto_refresh = setInterval(function ()
{
var last_id=$("ol#update li:last").attr("id");
$.getJSON("chat_json.php?q="+user,function(data)
{
$.each(data.posts, function(i,data)
{
if(last_id != data.id)
{
var div_data="<li id='"+data.id+"'><b>"+data.user+"</b>: "+data.msg+"</li>";
$(div_data).appendTo("ol#update");
}
});
});
}, 2000);
// Inserting records into chat table
$(document).ready(function()
{
$('.post').click(function()
{
var boxval = $("#content").val();
var user = '<?php echo $user;?>';
var dataString = 'user='+ user + '&msg=' + boxval;
if(boxval.length > 0)
{
$.ajax({
type: "POST",
url: "chatajax.php",
data: dataString,
cache: false,
success: function(html)
{
$("ol#update").append(html);
$('#content').val('');
$('#content').focus();
}
});
}
return false;
});
});
</script>
// HTML code
<div>
<form method="post" name="form" action="">
<input type='text' name="content" id="content" />
<input type="submit" value="Post" id="post" class="post"/>
</form>
</div>
<?php } ?>
include('db.php');
if($_GET['user'])
{
$user=$_GET['user'];
?>
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
var user='<?php echo $user;?>';
// Requesting to Database every 2 seconds
var auto_refresh = setInterval(function ()
{
var last_id=$("ol#update li:last").attr("id");
$.getJSON("chat_json.php?q="+user,function(data)
{
$.each(data.posts, function(i,data)
{
if(last_id != data.id)
{
var div_data="<li id='"+data.id+"'><b>"+data.user+"</b>: "+data.msg+"</li>";
$(div_data).appendTo("ol#update");
}
});
});
}, 2000);
// Inserting records into chat table
$(document).ready(function()
{
$('.post').click(function()
{
var boxval = $("#content").val();
var user = '<?php echo $user;?>';
var dataString = 'user='+ user + '&msg=' + boxval;
if(boxval.length > 0)
{
$.ajax({
type: "POST",
url: "chatajax.php",
data: dataString,
cache: false,
success: function(html)
{
$("ol#update").append(html);
$('#content').val('');
$('#content').focus();
}
});
}
return false;
});
});
</script>
// HTML code
<div>
<form method="post" name="form" action="">
<input type='text' name="content" id="content" />
<input type="submit" value="Post" id="post" class="post"/>
</form>
</div>
<?php } ?>
chatajax.php
Contains PHP code. Inserting records into chat table.
<?php
include('db.php');
if($_POST)
{
$user=htmlentities($_POST['user']);
$msg=htmlentities($_POST['msg']);
$user=mysql_escape_String($user);
$msg=mysql_escape_String($msg);
mysql_query("insert into chat(user,msg)values('$user','$msg')");
$sql=mysql_query("select id from chat where user='$user' order by id desc limit 1");
$row=mysql_fetch_array($sql);
$id=$row['id'];
?>
<li id="<?php echo $id; ?>">
<b><?php echo $user; ?>:</b><?php echo $msg;?>
</li>
<?php
}
?>
include('db.php');
if($_POST)
{
$user=htmlentities($_POST['user']);
$msg=htmlentities($_POST['msg']);
$user=mysql_escape_String($user);
$msg=mysql_escape_String($msg);
mysql_query("insert into chat(user,msg)values('$user','$msg')");
$sql=mysql_query("select id from chat where user='$user' order by id desc limit 1");
$row=mysql_fetch_array($sql);
$id=$row['id'];
?>
<li id="<?php echo $id; ?>">
<b><?php echo $user; ?>:</b><?php echo $msg;?>
</li>
<?php
}
?>
chat_json.php
Contains PHP code getting latest record from the chat table and output result in JSON format.
<?php
include('db.php');
if($_GET['q'])
{
$user=$_GET['q'];
$sql = mysql_query("select * from chat order by id desc limit 1");
$row=mysql_fetch_array($sql);
$userx=$row['user'];
$id=$row['id'];
$msg=$row['msg'];
if($userx!=$user)
{
echo '{"posts": [';
echo '
{
"id":"'.$id.'",
"user":"'.$userx.'",
"msg":"'.$msg.'"
},';
echo ']}';
} }
?>
include('db.php');
if($_GET['q'])
{
$user=$_GET['q'];
$sql = mysql_query("select * from chat order by id desc limit 1");
$row=mysql_fetch_array($sql);
$userx=$row['user'];
$id=$row['id'];
$msg=$row['msg'];
if($userx!=$user)
{
echo '{"posts": [';
echo '
{
"id":"'.$id.'",
"user":"'.$userx.'",
"msg":"'.$msg.'"
},';
echo ']}';
} }
?>
db.php
PHP database configuration file
<?php
$mysql_hostname = "Host name";
$mysql_user = "UserName";
$mysql_password = "Password";
$mysql_database = "Database Name";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select database");
?>
$mysql_hostname = "Host name";
$mysql_user = "UserName";
$mysql_password = "Password";
$mysql_database = "Database Name";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select database");
?>










link not working ..not able to see demo
Just add
$('#content').focus();
after
$(div_data).appendTo("ol#update");
In your chat.php
Very nice..keep on working on this..:D
hi man thank you for this example :D that is well
great job
this guy is something else on the internet....very generous giver....publishes pure life saving codes.....he made me to fall more in love with jquery library and it's beauty....i must say 10k u brother....u the best on the internet known for giving out very important codes....GOD BLESS U
Update : chatajax.php
please modify download script
Hello,
you got an XSS flaw in your script, $_GET['user'] isn't properly checked before outputting it on the page.
- Benjamin
sir can u make a tutorial on how to implement a message notification or comment notifications like facebook?? i really2x love ur tutorials
this looks amazing...great job
Hi Srinivas, for the JSON you can use echo json_encode($array);
I've never subscribed to any blog on the web. This one is going to be my first. But Srinivas remember that a bit explanation will save us a lot of time.
what script to calculate time posting? like the one on the demo page.
you're awesome!! really like your work!
Are you still working on this? :)
Demo script and script for download is two different script. In script for download there is no session for users. U can type text into text area and data will not be inserted into database and so on ....
nice example man...!!!
grt wrk .. !! :)
Is there a particular reason you're not using mysql_insert_id() in chatajax.php to get the id of the inserted message?
Hi, man. nice code, bit i had found a bit of mistakes. And i had fixed them for me. Thanks for idea.
Parse error: syntax error, unexpected '}', expecting ',' or ';' in /home/accounts_s/saver/public_html/chat/chat.php on line 174
Hi... can i have full chatting script? like what we login to the demo there.. i need it... thank you... hope u can reply me
not working on chrome. i can see only that i posted but not the posted by other people
thanks
unbelievable man!!! you r great. God bless you.
grate
Guys,
Using the downloaded code,
I ran the program with two firefox browser
sessions, one session for each user ,
for example one session as
chat.php?user=johndoe and the other session
as chat.php?userjanedone, I noticed that
database only inserted the first time johndoe or
janedoe posted the message . That means
there are only 2 entries in the database.
Subsequent posts by these two users do not get inserted into the database at all.
Is this the way the software supposed to work ?
Because of this fact, Output for each user
on their browser are not displaying correctly
as they are chatting .
looking in to it
good one
There is a bug created by your SQL
CREATE TABLE chat
(
id INT PRIMARY KEY AUTO_INCREMENT,
user VARCHAR(50) UNIQUE,
msg VARCHAR(200),
);
If you defined that user is UNIQUE, that means it is a status update and showing others' status application but not chatting.
hey this one is awesome man.
Thank you very much!!!!
Wow!
Im falling in love with this guy, his tutorials and jquery.
Great job guy. Keep it up.
Nice wor man. I have got problems with this script though.When you refresh it clears the chat screen. Also, I opened several browsers with different users chatting, i can only see the msg that user types and not the others. in the chat_json.php file i tried using a while loop to get the messages shown instead of just one. :( help please
Please write post about xmpp jabber.. and connect with gtalk
hmm coooll ....I tried of flash chat ...bt will implement it in my wbsite :) thanx
cool
Chatting plug in is extreemly awesome i must include this type of plug ins in my projects
Thanks
good job sir .. thankyou
Confused... where is the chat output?
Hi... can i have full chatting script? like what we login to the demo there.. i need it... thank you... hope u can reply me
when i'm running chat.php an error comes: "syntax error, unexpected $end" at last line. what could b d possibl reason and d rectification
NOT WORK
Not working.. Cant able to see demo
nice post man...but every msg inserted into table..that's crap...you need to store thess msgs to some text file...
CREATE TABLE chat
(
id INT PRIMARY KEY AUTO_INCREMENT,
user VARCHAR(50) UNIQUE,
msg VARCHAR(200),
);
error
I could not under the below code:
var last_id=$("ol#update li:last").attr("id");
from where it is getting the last id?
U r genius....I love u very much....
Nice man..U r genius.....
specify it clearly.....
thanks mate. i am going to try this
error ----
Notice: Undefined index: user in C:\wamp\www\myserver\chat.php on line 3
plz reply soon.
buddy : the below is the error I'm getting
Parse error: syntax error, unexpected '}', expecting ',' or ';' in C:\xampp\htdocs\chat.php on line 174
how could i get rectified
Thanks Man
Anyone Know how to use the above chat application in Asp.net and C# or VB
not working
Great!
it will be great if u can show us how to implement comet or reverse ajax instead of polling every 2 seconds... anyways good tutorial :)
not working this code...please help me am gettting ..Notice: Undefined index: user in C:\wamp\www\facebook\chat.php on line 4
Call Stack error
am geeting this error please help me..Notice: Undefined index: user in C:\wamp\www\facebook\chat.php on line 4
Call Stack
nice
Fine, except that this will choke with more than af few users on shared hosting.
nice job!!!!!!! Thanks a lot!
I really like your posts BUT , it is not scalable at all, requesting from the database every 2 seconds !!? so why we are using node.js !? and we are going to insert the chat record by record for each user !!?
good job
Kindly write in asp.net c#