Comments System Using Php, jQuery & Ajax

Posted under :
Download the script Check the demo

Comments or reviews are useful to keep interaction between you, your content and members of your website, this script present a simple clean looking comments system with jQuery and Ajax that you can add to your website, design is inspired from facebook and google+ comments, take a look to the demo…

Nothing is complicated, we will understand how everything is working :)
Let’s start!

First of all, and after we create the database, create the table that will contain all the comments

CREATE TABLE IF NOT EXISTS `comments` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(40) NOT NULL,
  `email` varchar(60) NOT NULL,
  `comment` text NOT NULL,
  `id_post` int(11) NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
);

The index file contain php code that it retreive the comments of specified post or page ($id_post) from the database

<?php 
    $sql = mysql_query("SELECT * FROM comments WHERE id_post = '$id_post'") or die(mysql_error());;
    while($affcom = mysql_fetch_assoc($sql)){ 
        $name = $affcom['name'];
        $email = $affcom['email'];
        $comment = $affcom['comment'];
        $date = $affcom['date'];

        // Get gravatar Image 
        // https://fr.gravatar.com/site/implement/images/php/
        $default = "mm";
        $size = 35;
        $grav_url = "http://www.gravatar.com/avatar/".md5(strtolower(trim($email)))."?d=".$default."&s=".$size;

    ?>
    <div class="cmt-cnt">
        <img src="<?php echo $grav_url; ?>" />
        <div class="thecom">
            <h5><?php echo $name; ?></h5><span data-utime="1371248446" class="com-dt"><?php echo $date; ?></span>
            <br/>
            <p>
                <?php echo $comment; ?>
            </p>
        </div>
    </div><!-- end "cmt-cnt" -->
    <?php } ?>

Using jQuery, the form is displaying after we click on the “Write a comment …”
If the user write the comment, we send using ajax the form data the the ajax file located in “ajax/add-comment.php”
The javascript code in the index file :

   $(function(){ 
        //alert(event.timeStamp);
        $('.new-com-bt').click(function(event){    
            $(this).hide();
            $('.new-com-cnt').show();
            $('#name-com').focus();
        });

        /* when start writing the comment activate the "add" button */
        $('.the-new-com').bind('input propertychange', function() {
           $(".bt-add-com").css({opacity:0.6});
           var checklength = $(this).val().length;
           if(checklength){ $(".bt-add-com").css({opacity:1}); }
        });

        /* on clic  on the cancel button */
        $('.bt-cancel-com').click(function(){
            $('.the-new-com').val('');
            $('.new-com-cnt').fadeOut('fast', function(){
                $('.new-com-bt').fadeIn('fast');
            });
        });

        // on post comment click 
        $('.bt-add-com').click(function(){
            var theCom = $('.the-new-com');
            var theName = $('#name-com');
            var theMail = $('#mail-com');

            if( !theCom.val()){ 
                alert('You need to write a comment!'); 
            }else{ 
                $.ajax({
                    type: "POST",
                    url: "ajax/add-comment.php",
                    data: 'act=add-com&id_post='+<?php echo $id_post; ?>+'&name='+theName.val()+'&email='+theMail.val()+'&comment='+theCom.val(),
                    success: function(html){
                        theCom.val('');
                        theMail.val('');
                        theName.val('');
                        $('.new-com-cnt').hide('fast', function(){
                            $('.new-com-bt').show('fast');
                            $('.new-com-bt').before(html);  
                        })
                    }  
                });
            }
        });

    });

In the ajax file we check the email adress using Gravatar to get the profile image, then we insert the comment in the database, if the comment is inserted we display the comment
The ajax file “add-comment.php”

<?php
extract($_POST);
if($_POST['act'] == 'add-com'):
	$name = htmlentities($name);
    $email = htmlentities($email);
    $comment = htmlentities($comment);

    // Connect to the database
	include('../config.php'); 
	
	// Get gravatar Image 
	// https://fr.gravatar.com/site/implement/images/php/
	$default = "mm";
	$size = 35;
	$grav_url = "http://www.gravatar.com/avatar/" . md5( strtolower( trim( $email ) ) ) . "?d=" . $default . "&s=" . $size;

	if(strlen($name) <= '1'){ $name = 'Guest';}
    //insert the comment in the database
    mysql_query("INSERT INTO comments (name, email, comment, id_post)VALUES( '$name', '$email', '$comment', '$id_post')");
    if(!mysql_errno()){
?>

    <div class="cmt-cnt">
    	<img src="<?php echo $grav_url; ?>" alt="" />
		<div class="thecom">
	        <h5><?php echo $name; ?></h5><span  class="com-dt"><?php echo date('d-m-Y H:i'); ?></span>
	        <br/>
	       	<p><?php echo $comment; ?></p>
	    </div>
	</div><!-- end "cmt-cnt" -->

	<?php } ?>
<?php endif; ?>


  • Márcio Melo

    How can i put a load more comments button in this code?

    • Guest

      twe btger

    • Guest

      tset

    • hGn

      2) On add-comment.php, below if($_POST[‘act’] == ‘add-com’): … $comment = check_input(htmlentities($comment, ENT_QUOTES));

      add soomething like:

      if($comment == ”) {
      echo ‘** Please, write a comment!’;
      exit;
      }

      and from the JS code, delete:

      if( !theCom.val()){
      alert(‘You need to write a comment!’);
      }else{

    • hGn

      To add a loader or change the SUBMIT button after click use some JS like:

      $(document).ready(function(){
      $(“:send_button_class”).click(function(){
      $(this).val(‘Submitting Comment’);
      $(this).css(‘opacity’,’0.5′);
      return true;
      });
      });

  • goggy

    it doesnt support utf-8 :( help …

    • Márcio Melo

      Change the lines 5,6,7 in ajax/add-comment.php to:

      $name = htmlentities($name, ENT_QUOTES, ‘UTF-8’);
      $email = htmlentities($email, ENT_QUOTES, ‘UTF-8’);
      $comment = htmlentities($comment, ENT_QUOTES, ‘UTF-8’);

      =)

      • Guest

        hello testing

        • guest

          dsdsds

          • guest

            asas

      • guest

        testing

        • guest

          ok done

          • guest

            asasas

          • guest

            saasas

          • Guest

            dsds

          • Guest

            dfsre

          • Guest

            sasasassdAA

          • mayan

            ok , its working

  • disqus_IRqT3SN88E
    • disqus_IRqT3SN88E

      de

  • eikelkop

    can you add pagination?

  • aliraza5

    well

  • tirelothomas

    Please help me out i get this : Warning: mysql_query(): Access denied for user ‘dendrons’@’localhost’ (using password: NO) in/home/dendrons/public_html/forum/index.php on line 22

    Warning: mysql_query(): A link to the server could not be established in/home/dendrons/public_html/forum/index.php on line 22
    Access denied for user ‘dendrons’@’localhost’ (using password: NO)

    • tirelothomas

      forum.dendronsecondary.co.za
      Please help me install the comment system on the server

      • all about the “config.php” file, just put the right host, database name, user and your password

        • mayan

          ok

  • vodys

    How edit DB & comments, when my charset on website is windows-1250?
    It doesn´t support “ěščřžýáíé”. Please, help :)

  • Borha

    How do I make this work with multiple instances of the comments. I have multiple blog posts on the same page. And I want each ‘comment’ section to work per blog.

    • Muzzukulu Wa Ndugwa

      Try to distinguish the js functions like this $(function(1){…… the numbers can change depending on which how many js scripts you want to load.

      • asd

        asd

        • asd

          asd asd

          • asd

            asd asd asd

          • asd

            asd asd asda asd

          • ,.scmd

            mewklejkw

          • pradeep chinwan

            bacaca

          • asd

            asdasdas das das

  • Muzzukulu Wa Ndugwa

    I ve tried several comment scripts and so far this one of WebCodo is far much pro. however, is it possible to get this config.php file?

  • sever2k7

    It’s working fine.
    But It’s have a small bug.
    Whe I use numeric id, it’s working fine.
    But when I use number+letter id, it’s doesn’t works.
    for example : $id_post = “xl34u”;

    How I can fix that problem?

    • Niko

      Because the $id_post field in the Database is “integer” type. You need to change it to “Varchar”

  • mayan

    yeahh

  • sheraz

    dx

  • Guest

    Nice tutorial

  • Ashok Kumar Sahoo

    Nice tutorial test

  • mohit

    nice

  • hGn

    Nice, very nice, simple, fast and easy to install! it worth it working on the admin cpanel and field validators, thank you!

  • hello any one to chating sysstem code in php

  • Chems Rachedi

    It would be nice if someone would tell me where this very comment system, yes the one you are reading this comment is from, it has everything. rate up / down reply and share
    mail me at chems_rac@live.com
    thank you

    • hGn

      This comment system is from disqus.com, at the bottom of the comment you can see the logo and info to add it to your site. It is really nice, it has everything, BUT is extremely HEAVY and SLOW.

  • Guest

    nice information

  • Abdelrahman Ragaey

    good work !

  • eliran

    very good :)

    • eliran

      yeah

  • Adam

    Nice one. A better one is the post/comments system that you are using on this page. Can you share the code? It is better to enable social login as keep track of user email/usernames.
    please shed some light..

    • hGn

      Go to DISQUS.com, this is the comment system this page using, the entire code isn’t public, but you can use this service in your site easily.

  • Good Stuff, and it works fine, thanks super easy to implement too, of course a few changes needed but overall easy.can you add pagination?

  • disqus_uCoEY8tpBJ

    n,

  • disqus_uCoEY8tpBJ

    httttttttttttttttt

  • sds d

    sdsd sds

  • sddads

    dsdsads

  • dvczx

    cxcxzxz

  • Guest

    Thanks bro you save my night and also you solve my problem

    • Curtis Newton

      why the fuck did you need to post your phot, faggot

    • Emil

      What are we supposed to do with your picture man???????

  • Rehan

    Thanks man you just save my night and solve my big problem again thanks.

  • df

    dfvfdvfdvfdv

  • df

    ergerg

  • df

    vbvbvbvbvbvbvbvbvbvbvbvbvbvbvbvbvbvbvbvbvbvbvbv

  • it

    iooiu

    • it

      mnm

  • ghgfh

    kjkjhkjhkjh

  • Niko

    Good job. Works well for me!

  • asdasd

    help please: mysql_fetch_array() expects parameter 1 to be resource, boolean given inC:xampphtdocsPost_Commentindex.php on line 22

  • Vivek

    how to create reply function??

  • koreya

    you make me to enjoy

  • Daniel
  • Matt Cote

    Is it possible to add oauth to this script?

  • Sampson Crowley

    modified the jquery a little:

    $(function(){
    function isEmail(email) {
    var regex = /^([a-zA-Z0-9_.+-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
    return regex.test(email);
    }
    function checkinput(){
    $(“.bt-add-com”).css({opacity:0.6});
    checklength = $(‘.the-new-com’).val().length;
    checkname = $(‘#name-com’).val().length;
    checkemail = isEmail($(‘#mail-com’).val());
    if(checklength > 10 && checkname > 3 && checkemail){ $(“.bt-add-com”).css({opacity:1}); }
    }
    //alert(event.timeStamp);
    $(‘.new-com-bt’).click(function(event){
    $(this).hide();
    $(‘.new-com-cnt’).show();
    $(‘#name-com’).focus();
    });

    /* when start writing the comment activate the “add” button */
    $(‘.the-new-com,#name-com,#mail-com’).keyup(checkinput);

    /* on clic on the cancel button */
    $(‘.bt-cancel-com’).click(function(){
    $(‘.the-new-com’).val(”);
    $(‘.new-com-cnt’).fadeOut(‘fast’, function(){
    $(‘.new-com-bt’).fadeIn(‘fast’);
    });
    });

    // on post comment click
    $(‘.bt-add-com’).click(function(){
    var theCom = $(‘.the-new-com’);
    var theName = $(‘#name-com’);
    var theMail = $(‘#mail-com’);

    if( !theCom.val()){
    alert(‘You need to write a comment!’);
    }else if(!theName.val()){
    alert(‘Name is required’);
    }else if(!theMail.val()){
    alert(‘Email is required’);
    }else{
    $.ajax({
    type: “POST”,
    url: “ajax/add-comment.php”,
    data: {
    act:’add-com’,
    id_post:,
    name:theName.val(),
    email:theMail.val(),
    comment:theCom.val()
    },
    success: function(html){
    theCom.val(”);
    theMail.val(”);
    theName.val(”);
    $(‘.new-com-cnt’).hide(‘fast’, function(){
    $(‘.new-com-bt’).show(‘fast’).before(html);
    })
    }
    });
    }
    });

    });

  • oddstake

    This is a good comments system but Disqus comments are better

  • You say create the database. How do I do that?

Be notified for new scripts