Live Comment System with jQuery Ajax PHP and MySQL

Recently I have been made a post that focused on how to submit form without page refreshing. That post shows the basic functionality of using jQuery Ajax. On the same follow this post will describe how we can create a comment system to post an instant comment without page refreshing. Let's start...


Demo Download Source
Database Design
We need to create two database table post and comment.

Post Table
The post table holds post data like post id, title, body or whatever you want. You need to inset some table rows. You will find it on demo.sql file.
CREATE TABLE `post` (
  `post_id` int(8) NOT NULL AUTO_INCREMENT,
  `post_title` varchar(124) NOT NULL,
  `post_body` text NOT NULL,
  PRIMARY KEY (`post_id`)
);
Comment Table
The comment table holds comment information. Here I only store commenter's name, mail and comment. If you want you can store more information like ip address, url or whatever you. Another thing you must to do, that to include is post id. It will tell you this comment is for which post.
CREATE TABLE `comment` (
  `id` int(8) NOT NULL AUTO_INCREMENT,
  `name` varchar(128) NOT NULL,
  `mail` varchar(128) NOT NULL,
  `comment` text NOT NULL,
  `post_id` int(8) NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
);
HTML Markup
This html code holds simple single post information. Post data will be placed in div.post and comments will be place in div.comment-block. We also need to add a comment form. I used here some html5 form properties, attributes and form validations like type="email", placeholder and required.
<html>
<head>
  <title>Comment System</title>
<head>
<body>
  <div class="post">
    <!-- post will be placed here from db -->
  </div>
  <div class="comment-block">
    <!-- comment will be apped here from db-->
  </div>
  <!-- comment form -->
  <form id="form" method="post">
    <!-- need to supply post id with hidden fild -->
    <input type="hidden" name="postid" value="1">
    <label>
      <span>Name *</span>
      <input type="text" name="name" id="comment-name" placeholder="Your name here...." required>
    </label>
    <label>
      <span>Email *</span>
      <input type="email" name="mail" id="comment-mail" placeholder="Your mail here...." required>
    </label>
    <label>
      <span>Your comment *</span>
      <textarea name="comment" id="comment" cols="30" rows="10" placeholder="Type your comment here...." required></textarea>
    </label>
    <input type="submit" id="submit" value="Submit Comment">
  </form>
</body>
</html>
JavaScript Code
This jQuery code is based on jQuery form submit event. When form submitted by user it sends a asynchronous request using jQuery.ajax method.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
  var form = $('form');
  var submit = $('#submit');

  form.on('submit', function(e) {
    // prevent default action
    e.preventDefault();
    // send ajax request
    $.ajax({
      url: 'ajax_comment.php',
      type: 'POST',
      cache: false,
      data: form.serialize(), //form serizlize data
      beforeSend: function(){
        // change submit button value text and disabled it
        submit.val('Submitting...').attr('disabled', 'disabled');
      },
      success: function(data){
        // Append with fadeIn see http://stackoverflow.com/a/978731
        var item = $(data).hide().fadeIn(800);
        $('.comment-block').append(item);

        // reset form and button
        form.trigger('reset');
        submit.val('Submit Comment').removeAttr('disabled');
      },
      error: function(e){
        alert(e);
      }
    });
  });
});
</script>
PHP Code
ajax_comment.php file holds this code. When the JavaScript sends asynchronous request this file receives serialized data and inserts into comment table. It also print out new comment for Ajax callback. Note, I haven't used any form validation code here. If you want to use it in real life project you must need to add form validation code.
<?php
// code will run if request through ajax
if (isset( $_SERVER['HTTP_X_REQUESTED_WITH'] )):
  include('config.php');
  include('function.php');
  // connecting to db
  dbConnect();
  
  if (!empty($_POST['name']) AND !empty($_POST['mail']) AND !empty($_POST['comment']) AND !empty($_POST['postid'])) {
    // preventing sql injection
    $name = mysql_real_escape_string($_POST['name']);
    $mail = mysql_real_escape_string($_POST['mail']);
    $comment = mysql_real_escape_string($_POST['comment']);
    $postId = mysql_real_escape_string($_POST['postid']);

    // insert new comment into comment table
    mysql_query("
      INSERT INTO comment
      (name, mail, comment, post_id)
      VALUES('{$name}', '{$mail}', '{$comment}', '{$postId}')");  
  }
?>
<!-- sending response with new comment and html markup-->
<div class="comment-item">
  <div class="comment-avatar">
    <img src="<?php echo avatar($mail) ?>" alt="avatar">
  </div>
  <div class="comment-post">
    <h3><?php echo $name ?> <span>said....</span></h3>
    <p><?php echo $comment?></p>
  </div>
</div>

<?php
  // close connection
  dbConnect(0);
endif?>

60 comments:

  1. Wow, this is amazing, it works! :)

    ReplyDelete
  2. Some security Issues

    ReplyDelete
  3. hello have been having this issue
    Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in H:\xampp\htdocs\dark_pro\index.php on line 458 can you please help me out with it

    ReplyDelete
    Replies
    1. check mysql table name on mysql_query or try to find out where is the error with mysql_error function.

      Delete
    2. Open index.php and locate this section:



      Then, change the ORDER BY comment_id DESC to ORDER BY id DESC

      Delete
  4. same probleme with "mysql_fetch-array()"
    ==> Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\wamp\www\jquery-ajax-comment-system\index.php on line 42

    ReplyDelete
    Replies
    1. There is no error! I think you have been made some mistake. Add a condition like this way mysql_query('my query...') or die(mysql_error()) on line 32. I hope it will tell you where is the error.

      Delete
    2. hello sir you awesome ,plz could you tell me how to create reply box

      Delete
  5. I want to use this script on several pages... Can you tell me how to give this comment box a specific ID? I would like to keep control over all the comments at once. I must know which comment comes from which page...

    ReplyDelete
  6. Hi ! thanks lot for your work, i use this script here for exemple :) http://mesdomaines.me/composant-18-template-bootstrap-exemple-7.html?d=&f=

    See you !

    ReplyDelete
  7. Just what i needed, thanks

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

    ReplyDelete
  9. Hi, I'm getting the following:

    Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\wamp\www\comment\index.php on line 42

    ReplyDelete
    Replies
    1. Appears to not like this:
      "SELECT *
      FROM comment
      WHERE post_id = {$row['post_id']}
      ORDER BY comment_id DESC
      LIMIT 15");

      Delete
    2. Changed it to this and now it works:
      $comment_query = mysql_query(
      "SELECT *
      FROM comment
      WHERE post_id = {$row['post_id']}
      ORDER BY id DESC
      Limit 15")or die(mysql_error());

      But now get :
      Warning: mysql_close() expects parameter 1 to be resource, null given in C:\wamp\www\function.php on line 10

      :(

      Delete
    3. I added the "or die(mysql_error())" to line 10 and now its working..

      :)

      Delete
  10. how can i use this i codeigniter? which floder should I put the file in?

    ReplyDelete
  11. it works but intergrating into a joomla site it just doesnt do anything

    ReplyDelete
  12. not working dynamically for instance to comment on different posts only one post works

    ReplyDelete
  13. thanks alot it took time to change it but still it helps and i m lovin it

    ReplyDelete
  14. i am getting this error " You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ORDER BY cmt_id DESC LIMIT 15' " at

    ReplyDelete
    Replies
    1. and i did this ...)or die(mysql_error());

      Delete
    2. I'm sorry, I don't get what you did exactly

      Delete
  15. where it says comment_id change it to post_id

    ReplyDelete
  16. still not working..... mysql_close($link)or die(mysql_error());

    Warning: mysql_close(): supplied argument is not a valid MySQL-Link resource in C:\wamp\www\\jquery-ajax-comment-system\function.php on line 10

    ReplyDelete
  17. I would have to wonder is this safe from XSS attacks?

    ReplyDelete
    Replies
    1. It is not safe from XSS and CSRF attacks!

      Delete
  18. How to make total comment like above ?

    ReplyDelete
  19. i tried wit dis code... but getting some error... how t solve dis????

    mysql_close($link)or die(mysql_error());

    Warning: mysql_close(): supplied argument is not a valid MySQL-Link resource in C:\wamp\www\\jquery-ajax-comment-system\function.php on line 10

    ReplyDelete
  20. I am displaying a list of product in a page and having comment box for each product in the same page.
    if i submit a comment, it will stored in multiple time(number of product comment form in the page).
    how to over come this problem.

    ReplyDelete
  21. Hello, thank you for the great work,
    everything works perfect, after I refresh the page all my comments disappear.
    What to do in order to keep them on the page,
    Thnak you.

    ReplyDelete
  22. which db should I enter it in?
    I 've made a db then put table codes and then edited the config file.
    still not working. how to make it working?

    ReplyDelete
  23. can not do anything with it - does not work right away in any way.

    ReplyDelete
  24. how to use this script on many pages????

    ReplyDelete
  25. This comment post thing is clashing with another script on my blog, when i login or click the login button on the sidebar it automatically posts a comment, and this script also causes my login to not work at all.

    could anyone please assist me to put this comment system's post process into another function, as the login also uses a similar if(isset$post process....

    ReplyDelete
  26. I'm having the following error:

    MySQL ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'ORDER BY id DESC Limit 15' at line 4

    Let me also add that I had to separate the html code from the php code and added the "action" attribute to the "form" tag because I was getting a "mysql_fetch_array" error.

    Any ideas please?

    ReplyDelete
  27. I would like to use it for my news system. But I do not know how I can adjust it on my system, since I use several news posts on a page. Is that even possible?

    ReplyDelete
  28. everytime i post a comment, then when i refresh the page the comment is gone. How can this be edit, so the comment stays?

    ReplyDelete
  29. How to add reply message for each comments. Hope you can help because it really urgent. thank you

    ReplyDelete
  30. &naruto werffw - Abdul Robinson - Bubblews
    Home Page

    ReplyDelete
  31. Hi this awesome but how could we add a reply button that indents the reply underneath?

    ReplyDelete

Go to top