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
Database
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
ReplyDeleteJust add
ReplyDelete$('#content').focus();
after
$(div_data).appendTo("ol#update");
In your chat.php
Very nice..keep on working on this..:D
ReplyDeletehi man thank you for this example :D that is well
ReplyDeletegreat job
ReplyDeletethis 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
ReplyDeleteUpdate : chatajax.php
ReplyDeleteplease modify download script
Hello,
ReplyDeleteyou 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
ReplyDeletethis looks amazing...great job
ReplyDeleteHi Srinivas, for the JSON you can use echo json_encode($array);
ReplyDeleteI'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.
ReplyDeletewhat script to calculate time posting? like the one on the demo page.
ReplyDeleteCURRENT TIMESTAPME .... search for somethings like that :)
Deleteyou're awesome!! really like your work!
ReplyDeleteAre you still working on this? :)
ReplyDeleteDemo 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 ....
ReplyDeletenice example man...!!!
ReplyDeletegrt wrk .. !! :)
Is there a particular reason you're not using mysql_insert_id() in chatajax.php to get the id of the inserted message?
ReplyDeleteHi, man. nice code, bit i had found a bit of mistakes. And i had fixed them for me. Thanks for idea.
ReplyDeleteParse error: syntax error, unexpected '}', expecting ',' or ';' in /home/accounts_s/saver/public_html/chat/chat.php on line 174
ReplyDeleteHi... can i have full chatting script? like what we login to the demo there.. i need it... thank you... hope u can reply me
ReplyDeletenot working on chrome. i can see only that i posted but not the posted by other people
ReplyDeletethanks
ReplyDeleteunbelievable man!!! you r great. God bless you.
ReplyDeletegrate
ReplyDeleteGuys,
ReplyDeleteUsing 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
ReplyDeletegood one
ReplyDeleteThere is a bug created by your SQL
ReplyDeleteCREATE 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.
ReplyDeleteThank you very much!!!!
ReplyDeleteWow!
ReplyDeleteIm 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
ReplyDeletePlease write post about xmpp jabber.. and connect with gtalk
ReplyDeletehmm coooll ....I tried of flash chat ...bt will implement it in my wbsite :) thanx
ReplyDeletecool
ReplyDeleteChatting plug in is extreemly awesome i must include this type of plug ins in my projects
ReplyDeleteThanks
good job sir .. thankyou
ReplyDeleteConfused... where is the chat output?
ReplyDeleteHi... can i have full chatting script? like what we login to the demo there.. i need it... thank you... hope u can reply me
ReplyDeletewhen i'm running chat.php an error comes: "syntax error, unexpected $end" at last line. what could b d possibl reason and d rectification
ReplyDeleteNOT WORK
ReplyDeleteNot working.. Cant able to see demo
ReplyDeletenice post man...but every msg inserted into table..that's crap...you need to store thess msgs to some text file...
ReplyDeleteCREATE TABLE chat
ReplyDelete(
id INT PRIMARY KEY AUTO_INCREMENT,
user VARCHAR(50) UNIQUE,
msg VARCHAR(200),
);
error
I could not under the below code:
ReplyDeletevar last_id=$("ol#update li:last").attr("id");
from where it is getting the last id?
U r genius....I love u very much....
ReplyDeleteNice man..U r genius.....
ReplyDeletespecify it clearly.....
ReplyDeletethanks mate. i am going to try this
ReplyDeleteerror ----
ReplyDeleteNotice: 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
ReplyDeleteParse error: syntax error, unexpected '}', expecting ',' or ';' in C:\xampp\htdocs\chat.php on line 174
how could i get rectified
Thanks Man
ReplyDeleteAnyone Know how to use the above chat application in Asp.net and C# or VB
ReplyDeletenot working
ReplyDeleteit will be great if u can show us how to implement comet or reverse ajax instead of polling every 2 seconds... anyways good tutorial :)
ReplyDeletenot working this code...please help me am gettting ..Notice: Undefined index: user in C:\wamp\www\facebook\chat.php on line 4
ReplyDeleteCall Stack error
am geeting this error please help me..Notice: Undefined index: user in C:\wamp\www\facebook\chat.php on line 4
ReplyDeleteCall Stack
nice
ReplyDeleteFine, except that this will choke with more than af few users on shared hosting.
ReplyDeletenice job!!!!!!! Thanks a lot!
ReplyDeleteI 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 !!?
ReplyDeletegood job
Kindly write in asp.net c#
ReplyDeleteProblem is if some user send a message at the same time, only the last one will be loaded.
ReplyDelete@chat.php
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
ReplyDeleteHey 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.
ReplyDeleteThank you ! For posting such awesome tutorials!!! gracias!!
ReplyDeleteThank you ! For posting such awesome tutorials!!! but how to chat only two person with this chat
ReplyDeletei am getting problem on Undefined index: user in C:\wamp\wwwchatting\chat.php on line 4 plz help me
ReplyDeleteI think I was able to fixed. Scirpt skipped some message when was them too many.
ReplyDeletein chat.php you can add last li
$.getJSON("chat_json.php?q="+user,function(data)
to
$.getJSON("chat_json.php?&last="+b+"&q="+user,function(data)
in chat_json.php must change
$user=$_GET['q'];
if(isset($_GET['last']) AND !empty($_GET['last']) AND $_GET['last'] != 'undefined')
$result = $this->db->query('SELECT * FROM chat WHERE id > "'.$_GET['last'].'" ORDER BY id ASC');
else
$result = $this->db->query('SELECT * FROM chat WHERE ORDER BY id DESC limit 1');
And change mysql_fetch_array to array.
This is a kind of group chat. How to implement one to one chatting? does anyone have idea?
ReplyDeletevery nice (but i have one doubt the why chat msg repeated twice)
ReplyDeleteI hope U ll provide a solution for this issue
This comment has been removed by the author.
ReplyDeleteNowadays you can setup web socket ...like socket.io instead of traditional jQuery
ReplyDelete