About Me

header ads

Comment System with Ajax, PHP & MySQL

Comment System with Ajax, PHP & MySQL

Comment system is an important part of web applications in which the website owner ask its readers or audience to give comments about contents or system. The comment system is useful for the content based websites because it increases the connection between owner and reader and also help to improve the quality of contents. So if you’re developing a web application using PHP and thinking about implementing comment system then you’re here at right place. In this tutorial you will learn how to develop comment system with Ajax, PHP and MySQL. Here we will cover this tutorial with live comment system example where user can post a new comment without page refresh using Ajax and also other users can reply to already posted comments at nth level.
As we will cover this tutorial with live example to develop comment system with Ajax, PHP and MySQL., so the major files for this example is following.
  • index.php
  • comments.js
  • comments.php
  • show_comments.php
Step1: Create Database Table
First we will will create MySQL database table comment to store comments details using below query.
CREATE TABLE `comment` (
`id` int(11) NOT NULL,
`parent_id` int(11) NOT NULL,
`comment` varchar(200) NOT NULL,
`sender` varchar(40) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `comment`
ADD PRIMARY KEY (`id`);
Step2: Create Comment Form with Bootstrap HTML
In index.php file, we will create Bootstrap HTML Form to post comments and display posted comments.
<div class="container">
<h2>Example: Comment System with Ajax, PHP & MySQL</h2>
<form method="POST" id="commentForm">
<div class="form-group">
<input type="text" name="name" id="name" class="form-control" placeholder="Enter Name" required />
</div>
<div class="form-group">
<textarea name="comment" id="comment" class="form-control" placeholder="Enter Comment" rows="5" required></textarea>
</div>
<span id="message"></span>
<div class="form-group">
<input type="hidden" name="commentId" id="commentId" value="0" />
<input type="submit" name="submit" id="submit" class="btn btn-primary" value="Post Comment" />
</div>
</form>
<div id="showComments"></div>
</div>
Step3: Handle Comment Post Functionality with Ajax
In comments.js file, we will handle Form submit using jQuery and make Ajax request to comments.php to save posted comments. We will also call function showComments() to display saved comments.
$(document).ready(function(){
$('#commentForm').on('submit', function(event){
event.preventDefault();
var formData = $(this).serialize();
$.ajax({
url: "comments.php",
method: "POST",
data: formData,
dataType: "JSON",
success:function(response) {
if(!response.error) {
$('#commentForm')[0].reset();
$('#commentId').val('0');
$('#message').html(response.message);
showComments();
} else if(response.error){
$('#message').html(response.message);
}
}
})
});
});
Step4: Save Comments into MySQL Database Table
In comments.php file, we will handle functionality to insert comments details into MySQL database table comment and return message with comments insert status.
<?php
if(!empty($_POST["name"]) && !empty($_POST["comment"])){
$insertComments = "INSERT INTO comment (parent_id, comment, sender) VALUES ('".$_POST["commentId"]."', '".$_POST["comment"]."', '".$_POST["name"]."')";
mysqli_query($conn, $insertComments) or die("database error: ". mysqli_error($conn));
$message = '<label class="text-success">Comment posted Successfully.</label>';
$status = array(
'error' => 0,
'message' => $message
);
} else {
$message = '<label class="text-danger">Error: Comment not posted.</label>';
$status = array(
'error' => 1,
'message' => $message
);
}
echo json_encode($status);
?>
Step5: Handle Comments Display with Ajax
In commenst.js file, we will create a function showComments() and make a Ajax request to show_comments.php file to load and display saved comments.
function showComments() {
$.ajax({
url:"show_comments.php",
method:"POST",
success:function(response) {
$('#showComments').html(response);
}
})
}
Step6: Get Comments from MySQL Database Table
In show_comments.php file, we will get comments from MySQL database table comment and return with created Bootstrap HTML to display. We will load nested comments by making recursive call to function getCommentReply() to load replied nested comments.
<?php
include_once("db_connect.php");
$commentQuery = "SELECT id, parent_id, comment, sender, date FROM comment WHERE parent_id = '0' ORDER BY id DESC";
$commentsResult = mysqli_query($conn, $commentQuery) or die("database error:". mysqli_error($conn));
$commentHTML = '';
while($comment = mysqli_fetch_assoc($commentsResult)){
$commentHTML .= '
<div class="panel panel-primary">
<div class="panel-heading">By <b>'.$comment["sender"].'</b> on <i>'.$comment["date"].'</i></div>
<div class="panel-body">'.$comment["comment"].'</div>
<div class="panel-footer" align="right"><button type="button" class="btn btn-primary reply" id="'.$comment["id"].'">Reply</button></div>
</div> ';
$commentHTML .= getCommentReply($conn, $comment["id"]);
}
echo $commentHTML;
?>
The function getCommentReply() and code to handle functionality to reply to posted comment is not published here with tutorial, you need to download source code to run complete example on your server.

Post a Comment

0 Comments