9lessons programming blog
Loading Search
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");
?>
Sponsored Links

Share this post

Comments
{ 40 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

Post a Comment

Subscribe now!Recent Posts

Categories

Subscribe now!Popular Posts

People Says

@9lessons thank you for the great tutorials, we truly appreciate your contributions to the design community.

Smashing Magazine

Like Me

follow me
products

9lessons labs

9lessons clouds

Android application

Chrome Extension