9lessons programming blog
Loading Search
9lessons Bring Friends
Wall Script
Follow Me:
Thursday, June 10, 2010

Chatting with Jquery and Ajax.

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 Demo

Database
CREATE TABLE chat
(
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 } ?>

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; ?&gt;">
<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 ']}';
} }
?>

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");
?>
Comments
{ 70 comments }
backendcode said...

link not working ..not able to see demo

bluepicaso said...

Just add
$('#content').focus();

after

$(div_data).appendTo("ol#update");

In your chat.php

Bogdan said...

Very nice..keep on working on this..:D

Anonymous said...

hi man thank you for this example :D that is well

Anonymous said...

great job

Anonymous said...

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

Srinivas Tamada said...

Update : chatajax.php

please modify download script

Benjamin Flesch said...

Hello,

you got an XSS flaw in your script, $_GET['user'] isn't properly checked before outputting it on the page.

- Benjamin

Anonymous said...

sir can u make a tutorial on how to implement a message notification or comment notifications like facebook?? i really2x love ur tutorials

infopediaonlinehere said...

this looks amazing...great job

Anonymous said...

Hi Srinivas, for the JSON you can use echo json_encode($array);

Alexander Suraphel said...

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.

q-wildz said...

what script to calculate time posting? like the one on the demo page.

pinzer said...

you're awesome!! really like your work!

bogdanxpose said...

Are you still working on this? :)

Anonymous said...

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

pacifik said...

nice example man...!!!
grt wrk .. !! :)

Anonymous said...

Is there a particular reason you're not using mysql_insert_id() in chatajax.php to get the id of the inserted message?

Gromit said...

Hi, man. nice code, bit i had found a bit of mistakes. And i had fixed them for me. Thanks for idea.

Zapytaj World said...

Parse error: syntax error, unexpected '}', expecting ',' or ';' in /home/accounts_s/saver/public_html/chat/chat.php on line 174

Anonymous said...

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

Anonymous said...

not working on chrome. i can see only that i posted but not the posted by other people

jedezo said...

thanks

anjana said...

unbelievable man!!! you r great. God bless you.

Anonymous said...

grate

Anonymous said...

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 .

Anonymous said...

looking in to it

Anonymous said...

good one

Steve said...

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.

Anonymous said...

hey this one is awesome man.

Anonymous said...

Thank you very much!!!!

Edric E. said...

Wow!
Im falling in love with this guy, his tutorials and jquery.

Great job guy. Keep it up.

Anonymous said...

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

Mohammad Shakeel said...

Please write post about xmpp jabber.. and connect with gtalk

Friends Social Network said...

hmm coooll ....I tried of flash chat ...bt will implement it in my wbsite :) thanx

Anonymous said...

cool

web designer chandigarh said...

Chatting plug in is extreemly awesome i must include this type of plug ins in my projects

Thanks

Faiq Qushoyyi said...

good job sir .. thankyou

Anonymous said...

Confused... where is the chat output?

Cong Nguyen said...

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

beginer said...

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

REALCOMMENT said...

NOT WORK

Anonymous said...

Not working.. Cant able to see demo

Anonymous said...

nice post man...but every msg inserted into table..that's crap...you need to store thess msgs to some text file...

منتديات ايبو said...

CREATE TABLE chat
(
id INT PRIMARY KEY AUTO_INCREMENT,
user VARCHAR(50) UNIQUE,
msg VARCHAR(200),
);
error

Anonymous said...

I could not under the below code:

var last_id=$("ol#update li:last").attr("id");

from where it is getting the last id?

MANIKANDAN said...

U r genius....I love u very much....

MANIKANDAN said...

Nice man..U r genius.....

Anonymous said...

specify it clearly.....

vinodh said...

thanks mate. i am going to try this

chandra shekhar gupta said...

error ----

Notice: Undefined index: user in C:\wamp\www\myserver\chat.php on line 3


plz reply soon.

Anonymous said...

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

Anonymous said...

Thanks Man

Gopinath said...

Anyone Know how to use the above chat application in Asp.net and C# or VB

Anonymous said...

not working

Anonymous said...

Great!

Anonymous said...

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

Prashanth Gunda said...

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

Prashanth Gunda said...

am geeting this error please help me..Notice: Undefined index: user in C:\wamp\www\facebook\chat.php on line 4
Call Stack

Gopikrishnan Shankaran said...

nice

Henrik Pedersen said...

Fine, except that this will choke with more than af few users on shared hosting.

Rimil Tudu said...

nice job!!!!!!! Thanks a lot!

tareq said...

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

SAURAV KUMAR said...

Kindly write in asp.net c#

Anonymous said...

Problem is if some user send a message at the same time, only the last one will be loaded.
@chat.php

Anonymous said...

hi, can you say how this code can be modified for admin and user chat.. that is admin can chat with 'n' users but user should be able to chat with admin alone.. can you pls help for this

Concerned said...

Hey author! I noticed you don't reply comments. Well, the script is not working. I tested it on firefox and I.E. It only loads the current users post and no one else's. I would love if look into it and correct it. I would be also glad if you reply this comment. Keep up the good work. Best regards.

Rakhi Dhavale said...

Thank you ! For posting such awesome tutorials!!! gracias!!

Rizwana Sultan said...

Thank you ! For posting such awesome tutorials!!! but how to chat only two person with this chat

abhishek verma said...

i am getting problem on Undefined index: user in C:\wamp\wwwchatting\chat.php on line 4 plz help me

Post a Comment