Chatting with Jquery and Ajax.
Wall Script
Wall Script
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");
?>
web notification

75 comments:

  1. link not working ..not able to see demo

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

    after

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

    In your chat.php

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

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

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

    ReplyDelete
  6. Update : chatajax.php

    please modify download script

    ReplyDelete
  7. Hello,

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

    - Benjamin

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

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

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

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

    ReplyDelete
    Replies
    1. CURRENT TIMESTAPME .... search for somethings like that :)

      Delete
  12. you're awesome!! really like your work!

    ReplyDelete
  13. Are you still working on this? :)

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

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

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

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

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

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

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

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

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

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

    ReplyDelete
  24. hey this one is awesome man.

    ReplyDelete
  25. Thank you very much!!!!

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

    Great job guy. Keep it up.

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

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

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

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

    Thanks

    ReplyDelete
  31. Confused... where is the chat output?

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

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

    ReplyDelete
  34. Not working.. Cant able to see demo

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

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

    ReplyDelete
  37. I could not under the below code:

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

    from where it is getting the last id?

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

    ReplyDelete
  39. specify it clearly.....

    ReplyDelete
  40. thanks mate. i am going to try this

    ReplyDelete
  41. error ----

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


    plz reply soon.

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

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

    ReplyDelete
  44. 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 :)

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

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

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

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

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

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

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

    ReplyDelete
  52. Thank you ! For posting such awesome tutorials!!! gracias!!

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

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

    ReplyDelete
  55. I think I was able to fixed. Scirpt skipped some message when was them too many.
    in 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.

    ReplyDelete
  56. This is a kind of group chat. How to implement one to one chatting? does anyone have idea?

    ReplyDelete
  57. very nice (but i have one doubt the why chat msg repeated twice)
    I hope U ll provide a solution for this issue

    ReplyDelete
  58. This comment has been removed by the author.

    ReplyDelete
  59. Nowadays you can setup web socket ...like socket.io instead of traditional jQuery

    ReplyDelete

mailxengine Youtueb channel
Make in India
X