This time I had developed Comment system with out refreshing page with jQuery, Ajax and PHP. In this application I had implemented with gravatar image. It's is useful and simple just some lines of code. Take a look at the live demo effect.
Updated Version :Click Here
![](https://lh3.ggpht.com/_N9kpbq3FL74/Si-Dh6eQd8I/AAAAAAAABy4/MWzniqJUPQ4/jqueryajaxcomments.png)
![](https://lh3.ggpht.com/_N9kpbq3FL74/Sd31pMC1aHI/AAAAAAAABg8/UAWFBvpGO6Y/down.png)
![](https://lh6.ggpht.com/_N9kpbq3FL74/Sd31o5XF8hI/AAAAAAAABg0/104nWJR7wro/live.png)
javascript code.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" >
$(function() {
$(".submit").click(function()
{
var name = $("#name").val();
var email = $("#email").val();
var comment = $("#comment").val();
var dataString = 'name='+ name + '&email=' + email + '&comment=' + comment;
if(name=='' || email=='' || comment=='')
{
alert('Please Give Valid Details');
}
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax-loader.gif" />Loading Comment...');
$.ajax({
type: "POST",
url: "commentajax.php",
data: dataString,
cache: false,
success: function(html){
$("ol#update").append(html);
$("ol#update li:last").fadeIn("slow");
$("#flash").hide();
}
});
}return false;
}); });
</script>
<script type="text/javascript" >
$(function() {
$(".submit").click(function()
{
var name = $("#name").val();
var email = $("#email").val();
var comment = $("#comment").val();
var dataString = 'name='+ name + '&email=' + email + '&comment=' + comment;
if(name=='' || email=='' || comment=='')
{
alert('Please Give Valid Details');
}
else
{$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax-loader.gif" />Loading Comment...');
$.ajax({
type: "POST",
url: "commentajax.php",
data: dataString,
cache: false,
success: function(html){
$("ol#update").append(html);
$("ol#update li:last").fadeIn("slow");
$("#flash").hide();
}
});
}return false;
}); });
</script>
comment.php
Contains HTML code here class timeline li{display:none}
<ol id="update" class="timeline">
</ol>
<div id="flash"></div>
<div >
<form action="#" method="post">
<input type="text" id="name"/>Name<br />
<input type="text" id="email"/>Email<br />
<textarea id="comment"></textarea><br />
<input type="submit" class="submit" value=" Submit Comment " />
</form>
</div>
commentajax.php
Contains PHP and HTML code.
<?php
if($_POST){
$name=$_POST['name'];
$email=$_POST['email'];
$comment=$_POST['comment'];
$lowercase = strtolower($email);
$image = md5( $lowercase );
mysql_query("SQL Comment table insert statement");
}
else { }
?>
<li class="box">
<img src="http://www.gravatar.com/avatar.php?gravatar_id=<?php echo $image; ?>"/>
<?php echo $name;?><br />
<?php echo $comment; ?>
</li>
More jQuery and Ajax Tutorials : Take a look at this link
best practice, thank you
ReplyDeleteCool! Thank you!
ReplyDeleteThe javascript is some obtrusive: when you disable javascript the form doesn't work. Better is posting to an existing page. With jQuery, you could change the action and do your AJAX thing.
ReplyDeletehey ... this is a very good script but what i wanted to know was that if i practically add something like this on my website then where do i store my comments .. how is this script going to change. please help me with this.... waitin..
ReplyDeleteYes where to store the comments :)
ReplyDeleteComments will store in database table..
ReplyDeleteCREATE TABLE comments
(
com_id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(25),
email VARCHAR(25),
comment TEXT
);
Edit " commentajax.php " SQL Statement
mysql_query("INSERT INTO comments (name,email,comment) VALUES ('$name','$email','$comment') ") ;
thanks for the fast reply , my mean is too keep
ReplyDeletethe comment on the page like when the comment
just come also
this character ' is transform to /
can we make clicable link from the comments ?
thanks and very good job :)
exactly what i was looking for, thanks
ReplyDeletenmn
ReplyDeletenice script but how to keep the comments visible ??
ReplyDeletehello! i love the script.. so i tried to change it a bit.. can you please show me how to add an input there as file? i want to add upload file using that script... please help me...
ReplyDeleteLooks perfect, thanks.
ReplyDeleteCan I get some clarification on what I need to do in order to store my posted comments here?
ReplyDeleteNamely, a better explanation of the following:
"Comments will store in database table..
CREATE TABLE comments
(
com_id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(25),
email VARCHAR(25),
comment TEXT
);
Edit " commentajax.php " SQL Statement
mysql_query("INSERT INTO comments (name,email,comment) VALUES ('$name','$email','$comment') ") ; "
Add one more column in "Comments" table
ReplyDeleteCREATE TABLE comments
(
com_id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(25),
email VARCHAR(25),
comment TEXT;
post_id INT // article or post ID
);
Alread comments table created.. use below statement.
ALTER TABLE comments ADD post_id INT;
Srinivas Tamada.
9lessons blog author
$dbhost = 'localhost';
ReplyDelete$dbuser = 'root';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'commentbox';
mysql_select_db($dbname);
Any help would be appreciated
My last comment cut off my question :S
ReplyDeleteI want to set up an SQL database to allow these comments to be saved. I have a basic knowledge of databases, but can anyone tell me how I set up the information I posted above to allow the comments to be saved?
The blog author's suggestion confused me slightly
Can anyone help me with selecting the comments from the database and displaying them in the same format? I can save them successfully but of course when you refresh the page they disappear.
ReplyDelete::lost::
ReplyDeleteAt this point I have a DB created, but even in reading everything here have no idea what I need to do next to be able to save these comments. I expected to actually see something in either comment.php or commentajax.php that asked me for the DB name, user and pass - something where'd I'd just plug these in and be good to go.
I need a "for dummies" version if someone should feel inclined. :/
Hi DsurioN
ReplyDeleteDisplaying existing Comments.
Step: 1
-------------------------------------
<ol id="update" class="timeline">
Include Step:2 Code here
</ol>
--------------------------------------
Step:2
--------------------------------
<?php
// Here 23 (post_id) article id
$sql=mysql_query("select * from comments where post_id='23' ");
while($row=mysql_fetch_array($sql) )
{
$name=$row['name'];
$email=$row['email'];
$comment=$row['comment'];
$lowercase = strtolower($email);
$image = md5( $lowercase );
?>
<li class="box">
<img src="http://www.gravatar.com/avatar.php?gravatar_id=
<?php echo $image; ?>"/>
<?php echo $name;?><br />
<?php echo $comment; ?>
</li>
<?php
}
?>
------------------------------------
hi Srinivas,
ReplyDeleteVery nice comment system , but i have one question , is it possible to make this script work in other languages such as Arabic ( right to left languages).
If so please tell me which files need to be changed...
Thanks man.
Thanks for keeping it simple. Just what I needed.
ReplyDeleteJIm
Hi Srinivas,
ReplyDeleteCan we have the final script with all the feature
request ? to be more clear im sure it's easy for you
but just for newbies like me :)
try it
ReplyDeleteHow can I revert the order where the li elements are placed? They are always placed 1 under the other... I would like to put one on topp of the other.
ReplyDeleteI tried changing $("ol#update li:FIRST").fadeIn("slow");
but it didnt work...
is there another way?
Hi Srinivas,
ReplyDeleteActually i m making a social community website. I have one problem here how can i show the comment post in the wesite once it is refreshed it is gone though it remains in the database.
Is there anything i have to do ?
What about security? When doing a comment system like this, you expose the php file that handles the post, and also the variables.
ReplyDeleteEveryone who knows php can access that php file directly, and add comments to non-existing blogs.
Is there a way to prevent this? I'm making a system like this myself, and I need som kind of security.
cool,,
ReplyDeletethank's for the sharing...
i will try it , ,,
You should be aware that if there is a lot of content in the comment box it looks a mess. The comment crosses over into the text fields.
ReplyDeleteSurprised nobody has noticed this. Tried it on the live demo in multiple browsers
Great turtorial. But if we have a lot of comments, how should we do next for the jquery pagination? Thankx
ReplyDeleteGreat explaination
ReplyDeletehow do you make this comment system to display the time when the comment was posted
ReplyDeletehi can this be themed like facebook
ReplyDeleteHey, Nice script m8.
ReplyDeleteBut if adding this to different pages while using the same db and table's will it only display the comments based on the page ID?
I see the post above and the additional table instructions but have yet to see if anyone actually got it working.
Any additional info would be greatly appreciated. Thanks :)
You should really make this a more complete script.
ReplyDeleteIts got great potential but its missing too many required pieces to be a viable option for anyone other than dev's.
Make a simple config file for mysql and include it with the download. It should also be built assuming people will be using it on multiple pages thus the post_id should be included by default.
hi can you explain the jQuery.js?
ReplyDelete-oscar
Hi Oscar,
ReplyDeletejQuery is great library for developing ajax based application. jQuery is the JavaScript Framework program, which simplifies the development of web applications. jQuery helps the programmers to keep code simple and concise. The jQuery library is designed to keep the things very simple and reusable.
Srinivas Tamada
thank you Srinivas Tamada,
ReplyDeletei just have another question how can fix the comment msg it overflows in the div i want it to be align on the div or if you have a final sourcecode can you share it to me im working on my personal page im just testing in at localhost..do you have email?thnx
Comments appear on top
ReplyDelete$("ol#update li:last").fadeIn("slow");
Change this into
$("ol#update li:first").fadeIn("slow");
how about captcha integration ?
ReplyDeleteSrinivas u r too gud yar... was looking fr the same thing
ReplyDeletePreeti
Wow great example i have edit it and it now shows comments has an captcha and posts to a DB also it works on multiple pages remembering wich page it has been posted to !!
ReplyDeleteGreat work
EFWGWERGRG
ReplyDeleteNice!
ReplyDeletecan i do pagging? in this script
ReplyDeleteHi Srinivas,
ReplyDeleteThanks for the script. I tried what you proposed to put one comment on top of the others
$("ol#update li:first").fadeIn("slow");
But it doesn't work. I can display the first comment but the others doens't appear. Can you help me?
thanks ya..
ReplyDelete@ David
ReplyDeleteComments appear on top
------------------------
You have two changes instead of the
$("ol#update").append(html);
$("ol#update li:last").fadeIn("slow");
to
$("ol#update").prepend(html);
$("ol#update li:first").fadeIn("slow");
Awesome! It works great. Thanks Srinivas
ReplyDeleteGreat Work
ReplyDeleteI can't see anywhere your mysql_close(); statement if you are to create tables in your database. Do you keep it opened and lying like that all the time just for everybody to access?
ReplyDeleteHello Srinivas,
ReplyDeleteI am lost on how to keep the old comments. What code and WHERE will I put it????
I am new to PHP and MySQL but very much interested in your work.
Hello Srinivas,
ReplyDeleteI am lost on how to keep the old comments posted and how to delete the old comments. What CODE and WHERE will I put it????
I am new to PHP and MySQL but very much interested in your work.
Many thanks!
Arnold
Hi Srinivas,
ReplyDeleteAll of us appreciated your work! Many thanks and keep it up.
Can you post here the complete COMMENT SYSTEM you have done.
Because for newbies like me, I am kinda loss with all additional codes. Like displaying the old comments, where to put the code, etc.
Again, thank you!
Updated This Post Link
ReplyDeleteComment System with jQuery, Ajax, PHP and MySQL (Version 2.0)
Hey, nice script.. with easy understanding :-)
ReplyDeletethanX
Manjula
thank you! very good!
ReplyDeleteWas wondering; the comments show above the form. How about making it into the reverse and have the comments show below the form. This format might be needed if just a single field is to be filled in. Think of something like Facebook's share form.
ReplyDeletegood job
ReplyDeleteThanks very nice
ReplyDeleteNICE!!!!!!
ReplyDeleteCool!
ReplyDeleteThank you
ReplyDeletenice
ReplyDeletehello tutorial how I can incorporate that into my site built with Joomla? which file should I edit, I use as a component joomsocial
ReplyDeletenice!!
ReplyDeletethank you
haha
ReplyDeleteThank you very much. Very usefull. Cheers! :)
ReplyDeletenice article, thanks
ReplyDeletethanks!
ReplyDeleteNice tutorial, thank you
ReplyDeleteGreat@@
ReplyDeleteTesing .. ajax is awsome
ReplyDeletevery nice
ReplyDeleteThis is cool
ReplyDeleteHello world!
ReplyDeleteHi,
ReplyDeleteYour code is terrible!! excelent work!
I just have a question. Is there a way to hide the location of commentajax.php from header? Cause the people can know where is it and try to access it directly.
Thanks
Real nice tutorial
ReplyDeleteAwesome
ReplyDeleteluvlyyyyyyyyyyyyyyyyyyyyyyy
ReplyDeleteThank you so mutch!
ReplyDeletevery nice
ReplyDeletecan you make clone of zendesk.com of give information how to make one thanks
HI
ReplyDeletehow can i show the comment post in my website once it is refreshed it is gone though it remains in the database.
Is there anything i have to do ?
@argentinoboy
ReplyDeleteRead following link ver 2.0
http://www.9lessons.info/2009/09/comment-system-database-with-jquery.html
Very good info. Thank you!
ReplyDeleteMaybe you can help me, how to make info not in ol tag but in table tag?
Thanks very much !!
ReplyDeleteInteresting
ReplyDeletethis is fine.......
ReplyDeletenice topic yar...
ReplyDeletethank you
ReplyDeletethx bro
ReplyDeleteTanks
ReplyDeleteits nice one
ReplyDeleteI modified the application to work with a database, you can download it here: http://www.getvay.com/pg/file/macs1407/read/1570/comentarios-es-jquery-php-mysql
ReplyDeletehow do I make an Image a PHP file??
ReplyDeleteGreat post! Thank you!
ReplyDeletelol, crashes in firefox
ReplyDeleteNICE
ReplyDeletePretty cool, been wondering how to do this for a while. :P
ReplyDeleteNice, thanks for that, just saved me a few hours.
ReplyDeleteHow do I change that avatar?! Please Help
ReplyDeletePS: Why are the comments dissappearing when you go in to the page again?
ReplyDeleteGreat script, but when you put a blank space( hit spacebar) in textarea, you can still post a blank comment. How to fix that ? Tnx
ReplyDeleteWarning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/a5530317/public_html/coment/comment.php
ReplyDeletewhat this mean?
how to fix please
Check the SQL statement
ReplyDeleteWow great example i have edit it and it now shows comments has an captcha and posts to a DB also it works on multiple pages remembering wich page it has been posted to !!
ReplyDeleteis this an example of the system itself?
ReplyDeletei love your script, you made me want to learn ajax now :)
ReplyDeleteexcelent
ReplyDeleteVery cool
ReplyDeleteWow, this is awesome!
ReplyDeleteI’ve implemented this and it works great. However, I’m having a hard time implementing multiple comment boxes on a single page. The best way to describe what I’m doing is to think of a twitter stream, and the users having the ability to view comments and add comments on each individual tweet. So I added another column to the comments table called item_id which will reference which item this comment belongs too. I’m not sure how to implement this though…..any help is greatly appreciated!!
thanks i like it...
ReplyDeletethanks
ReplyDeleteThe comment system is great when used in conjunction with JQuery,Ajax,CSS and PHP
ReplyDeletecool
ReplyDeleteAwesome I'll give it a try, got a complete account/profile settings system ready, people can sign up, log in and out alright. Now I'm going for how the site is gonna work.
ReplyDeleteCan't believe people are still using IE, it's such a pain in the ass to make the site compatible, not sure I'll do it anytime soon.
btw I'm following you on twitter ;)
cool
ReplyDeleteExcellent. Can't wait to give this a go, thanks.
ReplyDeleteNice job
ReplyDeletegood
ReplyDeletehi I am going to create admin page for comment system can you help me
ReplyDeletehi I am going to create admin page for comment system can you help me
ReplyDeleteNice comment system!
ReplyDeleteHow to implement 4(four) comment boxes on same page in 4 tabs (the comments need to be different)? And how to separate comments on different pages?
Thx a lot! sorry for my English.
just testing
ReplyDeletesame here
ReplyDeletehello guys may someone help me?
ReplyDeletemy problem is "Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/a5619214/public_html/com/comment.php Unknown column 'post_id'"
What ti do? Thank you
nice
ReplyDeleteThis is great! || Thank you for sharing! || :D
ReplyDeletegreat...
ReplyDeleteThis comment has been removed by a blog administrator.
ReplyDeleteHi Srinivas,
ReplyDeleteHow could i make this automatically update ? I can store the values, i can display them, but i would like to refresh the page everytime a new comment is added ( basically a chat function .. ). Any sugestions? Your help is greatly appreciated :) Thanks!
Hello again, i have figured this out on my own. It's not the best solution, but this is my add :
ReplyDeletein commentajax.php , instead of listing the last comment, you put the code to list all comments.
then, in your comment.php file, you create a function (ex: show_content() ) which contains the $.ajax code, without the data parameters. at the end of this function you add setTimeout("show_content()",2500); (2500 meaning 2.5 secs to refresh). You would need to clear the innerHTML of the update div, and remove the getElementByID('comment')="" statement, and than this can be used as a chat.
The instructions are short, but i can provide you the files so you can write more detailed instructions :) i'm sure people will be gratefull. My email is [email protected] (maybe you won't make this public,please!). Thanks!!!!
Alex.
nice. this is helpful
ReplyDeleteHello,
ReplyDeleteFirst of all i want to say a BIG thanks to Srinivas Tamada for this great work!
But am having a small problem, i've developed your script to be comment inside comments!
And my problem is i want to view the comment only on the current post.
$("ol#update"+ReplyID).append(html);
Its not working, can you please help?!
Thanks!
OMG, this is nice.
ReplyDeleteI will implement this in my own website if I have some spare time.
Thanks.
How to implement this comment system with php smarty template pages?
ReplyDeletePlease advice?
many thanks
ReplyDeletethanks
ReplyDeleteThank you....
ReplyDeleteAnd now how can i add spam filteer to this commenting system.
ReplyDeletethx. ..
ReplyDeleteAnd How to do with a "select" instead of "input"
ReplyDeletethx...
ReplyDeletethx
ReplyDeleteuh
ReplyDeletewhy dont you use these scripts on your site if they're so great?
good practics
ReplyDeletenice
ReplyDeleteMuito bom! Very good!
ReplyDeletevery nice
ReplyDeletedoes this site supports it?
ReplyDeletenice !!
ReplyDeletebut, i'm facing problem.. when i use newline in comment.. it crossed to next comment part.
How can i resolve it..help me !!
Its alright
ReplyDeleteThx
ReplyDeleteThank you so much <_>
ReplyDeleteThank you for this, works great :)
ReplyDeletenice info... thanks..
ReplyDeletethanks fo the information....
ReplyDeleteNice Comment System
ReplyDeletenice pretty cool but need to finish
ReplyDeleteNice comment box script. I might have to work on one myself.
ReplyDeleteI have added this code to my streamline, however after it posts the comment, I cannot get the text area to clear. Any thoughts?
ReplyDeletevery interesting cods thanks a lot
ReplyDeleteyou chose to make a click event on the submit button, it would be more intereting to use an onsubmit event listener...
ReplyDeleteFirts of all thanks for the script im new to js and jquery so as ajax, is very simple and understandable. I have a site with several posts on a single page, i want to add comments to every single one of them, how can i tell the script which form is been submited?
ReplyDeleteThanks!
thank!
ReplyDeleteThanks man !!!
ReplyDeleteGood work!
ReplyDeleteThank you for this script. But I have one question - how can I add more fields. I make everything to works fine but I can not make show post_id. I try to add input hidden field with post_id and after that i try to access it with $_POST[post_id] but... it's not working. I try to add one row it in the JavaScript:
ReplyDeletevar post_id = $("#post_id").val();
var name = $("#name").val();
var email = $("#email").val();
But it still not working :) Any suggestions?
cool..........
ReplyDeleteLooks good!!!
ReplyDeletePls can someone upload the working code and maybe post a link? is that possible here?. I really like this script, but it must be full of typo's or bugs judging by what people have commented on. Its an excellent looking comments system.
ReplyDeleteKev
good one...
ReplyDeletehow do i retain the comments while the page refreshes?...please any good assistance will be appreciated..thanks *
ReplyDelete###You can add more fields###
Just change the Id element name to your desired..and feel happy
################################
$(function() {
$(".submit").click(function()
{
var name = $("#name").val();
var email = $("#email").val();
var comment = $("#comment").val();
var Id = $("#actID").val();
var dataString = 'name='+ name + '&email=' + email + '&comment=' + comment + '&actID=' + Id;
if(name=='' || email=='' || comment=='')
{
alert('Please Give Valid Details');
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('(insert your loading image here)Loading Comment...');
$.ajax({
type: "POST",
url: "commentajax.php",
data: dataString,
cache: false,
success: function(html){
$("ol#update").append(html);
$("ol#update li:last").fadeIn("slow");
$("#flash").hide();
}
});
}return false;
}); });
it is great article.
ReplyDeleteis this script working with mobile web browsers?
ReplyDeleteNice script.
ReplyDeletecool one
ReplyDeletenice
ReplyDeleteHi guys See this PHP script:-
ReplyDeletethis script is good but has one major problem which i think most people would prefer to have, and that is to have the comments stream always display, and not just display when a comment is sent
ReplyDeletegood nice
ReplyDeletedoes this comment goes directly or goes for approval first?
ReplyDeleteNice sript, thanks man ! Just be good to add some function for paginatin comments - if we have moor comment about this article ?
ReplyDeleteBut, again, thanks man !
hi
ReplyDeletegood
ReplyDeletenice
ReplyDeletei'm trying this. thank you
ReplyDeleteI want only 10 comments once on a page than there shuld start a second and third page like youtube 1,2,3,4... . plz help me. Thanx
ReplyDeletepretty nice comments box!
ReplyDeleteIf I add the input selection through radio, what if it's in the validation "Please Give Details Valid".
ReplyDeleteHelp me.
Thanks
good
ReplyDeletevery good
ReplyDeletenice
ReplyDeletei need to delete the user what to do as a admin of my page?
ReplyDeletenice comment system! ;)
ReplyDeleteThis could lead to spam. How to delete comment ?
ReplyDeletenice
ReplyDeletethanks
ReplyDeletehi , sri this side puru....
ReplyDeletei just want to know that how did u make it mean ..the comment system in which i'm tyiping the words.
Thanks you :D
ReplyDeletethx
ReplyDelete