Friday, 29 December 2017

Comments System using PHP and Ajax

This time we are developing Simple Comment System by using PHP script with Ajax, Jquery, Bootstrap and Mysql Database. If you have seen our how to submit form data by using Ajax JQuery with PHP script without refresh of web page. So we have used same concept here for making Live commenting system by using PHP with Ajax and here comment will be submitted and display on web page without refresh of web page. In short we will make instant comment system without refresh of web page.

In this post we will not discuss simple Comment system in which only single user can submit their comment and nothing but here we have make nested comment system by using PHP code in which if one user has post comment then another user can also reply on that comment and add more review on that comment, and user can reply n level reply. So it will make simple social media system in which they can post their review on particular content. For making nested comment system we have use PHP recursive function which search child comment at n level.


We all know comment or even we can also called review are best way to keep make connection between website content owner and reader of that content. So this script will help you if have use non wordpress site then in that system you can use this type of script for providing user to share their review or feedback regarding your content. Commenting are the best way to exchange ideas for made best website content like article or blog. So for this all reason we have make this Live comment system by using PHP script with Ajax JQuery.








Source Code


index.php



<?php
//index.php

?>
<!DOCTYPE html>
<html>
 <head>
  <title>Comment System using PHP and Ajax</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <h2 align="center"><a href="#">Comment System using PHP and Ajax</a></h2>
  <br />
  <div class="container">
   <form method="POST" id="comment_form">
    <div class="form-group">
     <input type="text" name="comment_name" id="comment_name" class="form-control" placeholder="Enter Name" />
    </div>
    <div class="form-group">
     <textarea name="comment_content" id="comment_content" class="form-control" placeholder="Enter Comment" rows="5"></textarea>
    </div>
    <div class="form-group">
     <input type="hidden" name="comment_id" id="comment_id" value="0" />
     <input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
    </div>
   </form>
   <span id="comment_message"></span>
   <br />
   <div id="display_comment"></div>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 
 $('#comment_form').on('submit', function(event){
  event.preventDefault();
  var form_data = $(this).serialize();
  $.ajax({
   url:"add_comment.php",
   method:"POST",
   data:form_data,
   dataType:"JSON",
   success:function(data)
   {
    if(data.error != '')
    {
     $('#comment_form')[0].reset();
     $('#comment_message').html(data.error);
     $('#comment_id').val('0');
     load_comment();
    }
   }
  })
 });

 load_comment();

 function load_comment()
 {
  $.ajax({
   url:"fetch_comment.php",
   method:"POST",
   success:function(data)
   {
    $('#display_comment').html(data);
   }
  })
 }

 $(document).on('click', '.reply', function(){
  var comment_id = $(this).attr("id");
  $('#comment_id').val(comment_id);
  $('#comment_name').focus();
 });
 
});
</script>



add_comment.php



<?php

//add_comment.php

$connect = new PDO('mysql:host=localhost;dbname=testing', 'root', '');

$error = '';
$comment_name = '';
$comment_content = '';

if(empty($_POST["comment_name"]))
{
 $error .= '<p class="text-danger">Name is required</p>';
}
else
{
 $comment_name = $_POST["comment_name"];
}

if(empty($_POST["comment_content"]))
{
 $error .= '<p class="text-danger">Comment is required</p>';
}
else
{
 $comment_content = $_POST["comment_content"];
}

if($error == '')
{
 $query = "
 INSERT INTO tbl_comment 
 (parent_comment_id, comment, comment_sender_name) 
 VALUES (:parent_comment_id, :comment, :comment_sender_name)
 ";
 $statement = $connect->prepare($query);
 $statement->execute(
  array(
   ':parent_comment_id' => $_POST["comment_id"],
   ':comment'    => $comment_content,
   ':comment_sender_name' => $comment_name
  )
 );
 $error = '<label class="text-success">Comment Added</label>';
}

$data = array(
 'error'  => $error
);

echo json_encode($data);

?>


fetch_comment.php



<?php

//fetch_comment.php

$connect = new PDO('mysql:host=localhost;dbname=testing', 'root', '');

$query = "
SELECT * FROM tbl_comment 
WHERE parent_comment_id = '0' 
ORDER BY comment_id DESC
";

$statement = $connect->prepare($query);

$statement->execute();

$result = $statement->fetchAll();
$output = '';
foreach($result as $row)
{
 $output .= '
 <div class="panel panel-default">
  <div class="panel-heading">By <b>'.$row["comment_sender_name"].'</b> on <i>'.$row["date"].'</i></div>
  <div class="panel-body">'.$row["comment"].'</div>
  <div class="panel-footer" align="right"><button type="button" class="btn btn-default reply" id="'.$row["comment_id"].'">Reply</button></div>
 </div>
 ';
 $output .= get_reply_comment($connect, $row["comment_id"]);
}

echo $output;

function get_reply_comment($connect, $parent_id = 0, $marginleft = 0)
{
 $query = "
 SELECT * FROM tbl_comment WHERE parent_comment_id = '".$parent_id."'
 ";
 $output = '';
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $count = $statement->rowCount();
 if($parent_id == 0)
 {
  $marginleft = 0;
 }
 else
 {
  $marginleft = $marginleft + 48;
 }
 if($count > 0)
 {
  foreach($result as $row)
  {
   $output .= '
   <div class="panel panel-default" style="margin-left:'.$marginleft.'px">
    <div class="panel-heading">By <b>'.$row["comment_sender_name"].'</b> on <i>'.$row["date"].'</i></div>
    <div class="panel-body">'.$row["comment"].'</div>
    <div class="panel-footer" align="right"><button type="button" class="btn btn-default reply" id="'.$row["comment_id"].'">Reply</button></div>
   </div>
   ';
   $output .= get_reply_comment($connect, $row["comment_id"], $marginleft);
  }
 }
 return $output;
}

?>


Database



--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_comment`
--

CREATE TABLE IF NOT EXISTS `tbl_comment` (
  `comment_id` int(11) NOT NULL,
  `parent_comment_id` int(11) NOT NULL,
  `comment` varchar(200) NOT NULL,
  `comment_sender_name` varchar(40) NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_comment`
--
ALTER TABLE `tbl_comment`
  ADD PRIMARY KEY (`comment_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_comment`
--
ALTER TABLE `tbl_comment`
  MODIFY `comment_id` int(11) NOT NULL AUTO_INCREMENT;

113 comments:

  1. Wonderful tutorial. Keep it going and Happy New Year.

    ReplyDelete
  2. Thanks for your code and for your video tutorial

    ReplyDelete
  3. how does this work with mobile devices and multiple replies?

    ReplyDelete
  4. will this work as a live system

    ReplyDelete
  5. prettify js how to use please tell me....

    ReplyDelete
  6. hey! how to i use mysqli because with mysql is giving me error

    ReplyDelete
  7. nice tutorial, i have a problem i would like to echo the comments only related to a particular post, and not all

    ReplyDelete
  8. Checkout my commenting system i built using PHP and AJAX -

    https://haymkarran.com/comments.php

    ReplyDelete
  9. Puedes ayudarme con la paginacion de este tutorial

    ReplyDelete
  10. Thanks for this awesome tutorial! Further on, can you teach us please how to bring down the comment form under a specific comment when we click the reply button?

    ReplyDelete
  11. how can I replace comment_name by the name of a user who is already logged in?

    ReplyDelete
  12. please help me how can I change name of database

    ReplyDelete
  13. sorry...when I click submit nothing happens!! what is the problem?

    ReplyDelete
  14. what if we have many other post and we want each post to have its comment

    ReplyDelete
  15. Thank you Very much;
    Its working;

    ReplyDelete
  16. Hi I deployed this code but its not working. My hosting company advised me to connect with database like this although:

    $servername = "localhost";
    $username = "JMainol";
    $password = "xxxxx_";
    $databases = "Blog_Dream_Eco_Safari";

    $connect = mysqli_connect($servername, $JMainol, $password, $databases);

    I dont know where the problem can be

    ReplyDelete
  17. how do i also send post_id to the database

    ReplyDelete
  18. how can I can set the condition so that the name of the person who is logged is displayed directly as the comment author?

    ReplyDelete
    Replies
    1. Hey, you can capture the name of the person using the session id of the user currently logged in.

      Delete
    2. follow the steps :
      1- login form
      2- session condition for sessions start (); is sessions is started and everything is ok then u let the code of form have to be with echo form etc...
      3- replace the session varible with the name of input box and let the input box have to be hidden then make a event as onfocus for input comment box "so name input box = session varible "
      got it ?

      Delete
  19. how to send post id and fetch the exact comment which are on a particular post

    ReplyDelete
    Replies
    1. Very helpful. I have integrated this with my code-igniter application and it works perfectly.

      Delete
    2. i have tried but it not work with code-igniter

      Delete
    3. How did you integrate into your application? I have an application, but can't figure out how to add a comment to an existing article.

      Delete
  20. What is i am making a doctor portal and each doctor is given the choice to post an article and this article should be visible on both his and home page for all users.

    ReplyDelete
    Replies
    1. we will tell the webslesson admin to make a section for a users chat for better live question and answers

      Delete
  21. i have uploaded this script to my domain directory and do some changes also in fetchcomment.php and addcomment.php by changing their database name but its not working

    ReplyDelete
  22. sir, when we refresh the page it shows form resubmition error!
    what should I do for this

    ReplyDelete
  23. Worked perfect for me, Thanks!

    ReplyDelete
  24. hello sir can you add delete function, that would really be great. Thank you.

    ReplyDelete
  25. please how to Include Add_comment.php and Fecth_comment.php in Index.php

    ReplyDelete
  26. Can you help me out with the newer version of FullCalander Version 4?
    There are some different's there and i don't know how i can get it working. Kind regards Pepijn

    ReplyDelete
  27. how to implement it with code-igniter

    ReplyDelete
  28. great! I had been looking for something like that for days - going cracy. Could you, however, give any recommendation on how to use this of different pages? Would be highly appreciated.

    ReplyDelete
  29. and could you maybe give an idea about what I just got from you after my last post: "your comment will be .. approval" - how is this to be done?

    ReplyDelete
  30. I had a weird effect: I posted to test markup language, , , and tags, the first and last ones work fine, the tag however changed the whole text and not just the enclosing text plus! all prior comments to bold. And I do not like so much that anyone can mess up my whole design. You have any explanation for this? are there more tags that do such stuff, and how to avoid it? Note: before I used this I had substituted the b-tags in the add_comment_php and fetch_command.phh files; also it would be nice, if the number of total comments could be displayed somewhere. I appreciate your efforts, script is very nice apart from the bold thing

    ReplyDelete
  31. This is the best and simplest tutorial I've ever seen. Well done!

    ReplyDelete
  32. add_comment.php why display the code of error on the webpage

    ReplyDelete
  33. Thank you for this sir, it really helpfull... but how can i connect my post with comments post ???

    ReplyDelete
  34. Sir wiil you please make a multilevel real time commenting system with laravel ajax.... thanks

    ReplyDelete
  35. Thank you. Very very thank you for this comment system.

    ReplyDelete
  36. When I run this code over my local host it works properly but shows 500 error over the real server could anybody please sort out this problem.

    ReplyDelete
  37. Would be awesome if you could add toogle replies with ajax.

    ReplyDelete
  38. would be awesome if you could add toogle replies with ajax

    ReplyDelete
  39. Fatal error: Uncaught PDOException: PDO::__construct(): php_network_getaddresses: getaddrinfo failed: Name or service not known in /homepages/29/d775487527/htdocs/comment/fetch_comment.php:5 Stack trace: #0 /homepages/29/d775487527/htdocs/comment/fetch_comment.php(5): PDO->__construct('mysql:host=loca...', 'root', '') #1 {main} Next PDOException: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known in /homepages/29/d775487527/htdocs/comment/fetch_comment.php:5 Stack trace: #0 /homepages/29/d775487527/htdocs/comment/fetch_comment.php(5): PDO->__construct('mysql:host=loca...', 'root', '') #1 {main} thrown in /homepages/29/d775487527/htdocs/comment/fetch_comment.php on line 5

    ReplyDelete
  40. It works, but doesn't add any data to the database.

    ReplyDelete
  41. It is interesting to see more and more websites and blogs come up with the nested commenting system. It sure is an encouragement to people to comment and communicate causing a better interaction, especially in case of marketing blogs. Keep sharing more views, tips and suggestions about such innovative options in your posts. See more at https://www.metasyssoftware.com/

    ReplyDelete
  42. some help plz

    Warning: PDO::__construct() [pdo.--construct]: [2002] Une tentative de connexion a �chou� car le parti connect� n�a pa (trying to connect via tcp://localhost:3306) in D:\projets\web\infographieClasse\comment\fetch_comment.php on line 5

    Fatal error: Maximum execution time of 30 seconds exceeded in D:\projets\web\infographieClasse\comment\fetch_comment.php on line 5

    ReplyDelete
  43. Will this work with index.html instead of index.php?

    ReplyDelete
  44. there's an error in fetch_comment line5

    ReplyDelete
  45. how can i delete or update my reply sir :o

    ReplyDelete
  46. Did this work for somebody once altogether?

    ReplyDelete
  47. i copy and paste the code but it keep posting double value and also submit value when page is refreshed how to fix that

    ReplyDelete
  48. Hi there everyone, I have come across almost all the web development sites. However, your website is far better than other in form of content, tools and easiness of using website. Since I am a developer, I am always looking forward to make people aware of web development tools. I can help you people out by introducing you to range of json tools. Here is the link https://jsononline.net/.

    ReplyDelete

  49. Fatal error: Uncaught Error: Call to undefined method mysqli_stmt::fetchAll() in C:\xampp\htdocs\comment\fetch_comment.php:21 Stack trace: #0 {main} thrown in C:\xampp\htdocs\comment\fetch_comment.php on line 21

    I've done this more than 3 times and it still gives the same error.I think the problem is from the 'fetch_comment.php' file, from the 'fetchAll()' function.
    PLEASE I NEED YOUR HELP RIGHT AWAY. Thanks in advance.

    ReplyDelete
  50. very nice post :) Thank You For This Post :-) Keep it up.
    Random Number Generator
    YTS Torrent Magnet

    ReplyDelete
  51. Lo he probado me ha parecido que esta muy bien son pocos archivos y realmente funciona muy bien, quizás añadiría un sistema de captcha , porque uno de los peores problemas de crear un sistema de comentarios es es el spam

    ReplyDelete
  52. It's not working. Can you do one in procedural for the database part?

    ReplyDelete
  53. hi had added new two columns of like and unlike i also have added buttons respectively nearby the reply i want to update the database by 1 when users click the like or unlike button can u please guide me with this

    ReplyDelete
  54. It's really helpful tips about comments using php & ajax.

    ReplyDelete
  55. How to use the database, I mean what extension and all to use?

    ReplyDelete
  56. This comment system work properly localhost but not working my godaddy server pse help

    ReplyDelete
  57. can u tell me how u create this comment section ?

    ReplyDelete
  58. hey I am not able to make this system i am not able to sent the message plz help out

    ReplyDelete
  59. plz provide to download the source code

    ReplyDelete
  60. Thanks for sharing such informative post with us regarding creating a comment system in PHP

    ReplyDelete
  61. its ok for send ,but i see nothing in the page,its the same of demo,i dont understand
    why calendar ist not working

    ReplyDelete