Comments System using PHP and Ajax

by Vincy. Last modified on July 9th, 2022.

In this tutorial, we are going to see how to create an AJAX based simple comment system using PHP. This comments system includes features to add reply for any comments added by the user.

I have used jQuery AJAX to add the comment, reply to the database and show them to the users. As it uses the AJAX, it will give a seamless experience to the user. This is designed for an unlimited level threaded comments reply.

Each comment will have a unique id and this id will be used to refer the HTML element showing the comment. This comment id will be passed via an AJAX call to perform the comment oriented operations like adding replies.

In a previous tutorial, we have seen how to read and write to the database via an AJAX call.

The following screenshot shows the output for the PHP AJAX comment system.

Comments system output

HTML Code for Displaying Comments

This code shows the HTML input fields to enter the name and the comment/reply to be published. On submitting the user’s comment, the AJAX call will be invoked to add the data to the database. The AJAX code will add or append the comment/reply posted by the user after successful AJAX operations.

The comments and the replies are added in a structural view as a parent-child elements. Each comment is displayed by using a parent element containing the list of child elements which shows its replies.

index.php

<html>
<head>
<style>
body {
	font-family: Arial;
	width: 600px;
}

.comment-form-container {
	background: #F0F0F0;
	border: #e0dfdf 1px solid;
	padding: 20px;
	border-radius: 4px;
}

.input-row {
	margin-bottom: 20px;
}

.input-field {
	width: 100%;
	border-radius: 4px;
	padding: 10px;
	border: #e0dfdf 1px solid;
}

.btn-submit {
	padding: 10px 20px;
	background: #333;
	border: #1d1d1d 1px solid;
	color: #f0f0f0;
	font-size: 0.9em;
	width: 100px;
	border-radius: 4px;
	cursor: pointer;
}

ul {
	list-style-type: none;
}

.comment-row {
	border-bottom: #e0dfdf 1px solid;
	margin-bottom: 15px;
	padding: 15px;
}

.outer-comment {
	background: #F0F0F0;
	padding: 20px;
	border: #dedddd 1px solid;
	border-radius: 4px;
}

span.comment-row-label {
	color: #484848;
}

span.posted-by {
	font-weight: bold;
}

.comment-info {
	font-size: 0.9em;
	padding: 0 0 10px 0;
}

.comment-text {
	margin: 10px 0px 30px 0;
}

.btn-reply {
	color: #2f20d1;
	cursor: pointer;
	text-decoration: none;
}

.btn-reply:hover {
	text-decoration: underline;
}

#comment-message {
	margin-left: 20px;
	color: #005e00;
	display: none;
}

.label {
	padding: 0 0 4px 0;
}
</style>
<title>Comment System using PHP and Ajax</title>
<script src="jquery-3.2.1.min.js"></script>


<body>
	<h1>Comment System using PHP and Ajax</h1>
	<div class="comment-form-container">
		<form id="frm-comment">
			<div class="input-row">
				<div class="label">Name:</div>
				<input type="hidden" name="comment_id" id="commentId" /> <input
					class="input-field" type="text" name="name" id="name"
					placeholder="Enter your name" />
			</div>
			<div class="input-row">
				<textarea class="input-field" name="comment" id="comment"
					placeholder="Your comment here"></textarea>
			</div>
			<div>
				<input type="button" class="btn-submit" id="submitButton"
					value="Publish" />
				<div id="comment-message">Comment added successfully.</div>
			</div>
		</form>
	</div>
	<div id="output"></div>
	<script>
            function postReply(commentId) {
                $('#commentId').val(commentId);
                $("#name").focus();
            }

            $("#submitButton").click(function () {
            	   $("#comment-message").css('display', 'none');
                var str = $("#frm-comment").serialize();

                $.ajax({
                    url: "comment-add.php",
                    data: str,
                    type: 'post',
                    success: function (response)
                    {
                        var result = eval('(' + response + ')');
                        if (response)
                        {
                        	$("#comment-message").css('display', 'inline-block');
                            $("#name").val("");
                            $("#comment").val("");
                            $("#commentId").val("");
                     	   listComment();
                        } else
                        {
                            alert("Failed to add comments !");
                            return false;
                        }
                    }
                });
            });

            $(document).ready(function () {
            	   listComment();
            });

            function listComment() {
                $.post("comment-list.php",
                        function (data) {
                           var data = JSON.parse(data);

                            var comments = "";
                            var replies = "";
                            var item = "";
                            var parent = -1;
                            var results = new Array();

                            var list = $("<ul class='outer-comment'>");
                            var item = $("<li>").html(comments);

                            for (var i = 0; (i < data.length); i++)
                            {
                                var commentId = data[i]['comment_id'];
                                parent = data[i]['parent_comment_id'];

                                if (parent == "0")
                                {
                                    comments = "<div class='comment-row'>"+
                                    "<div class='comment-info'><span class='comment-row-label'>from</span> <span class='posted-by'>" + data[i]['comment_sender_name'] + " </span> <span class='comment-row-label'>at</span> <span class='posted-at'>" + data[i]['comment_at'] + "</span></div>" +
                                    "<div class='comment-text'>" + data[i]['comment'] + "</div>"+
                                    "<div><a class='btn-reply' onClick='postReply(" + commentId + ")'>Reply</a></div>"+
                                    "</div>";

                                    var item = $("<li>").html(comments);
                                    list.append(item);
                                    var reply_list = $('<ul>');
                                    item.append(reply_list);
                                    listReplies(commentId, data, reply_list);
                                }
                            }
                            $("#output").html(list);
                        });
            }

            function listReplies(commentId, data, list) {
                for (var i = 0; (i < data.length); i++)
                {
                    if (commentId == data[i].parent_comment_id)
                    {
                        var comments = "<div class='comment-row'>"+
                        " <div class='comment-info'><span class='comment-row-label'>from</span> <span class='posted-by'>" + data[i]['comment_sender_name'] + " </span> <span class='comment-row-label'>at</span> <span class='posted-at'>" + data[i]['comment_at'] + "</span></div>" +
                        "<div class='comment-text'>" + data[i]['comment'] + "</div>"+
                        "<div><a class='btn-reply' onClick='postReply(" + data[i]['comment_id'] + ")'>Reply</a></div>"+
                        "</div>";
                        var item = $("<li>").html(comments);
                        var reply_list = $('<ul>');
                        list.append(item);
                        item.append(reply_list);
                        listReplies(data[i].comment_id, data, reply_list);
                    }
                }
            }
        </script>
</body>
</html>

PHP Code to Publish Comment/Reply

In this PHP code, it receives AJAX request and adds the comment/reply posted by the user. After adding the user comments to the database, the PHP code will print the comment which will be read as a response to the AJAX script.

Comments system database

This response data will be appended to the comments HTML container. The following code shows the PHP program to add and show comments posted by the user via AJAX.

DataSource.php is a common database utility class. It is available in the project download zip linked at the end of this article.

comment-list.php

<?php
/**
 * This script is to list the comments in a nested order.
 */
use Phppot\DataSource;
require_once __DIR__ . '/DataSource.php';
$database = new DataSource();
$sql = "SELECT * FROM tbl_comment ORDER BY parent_comment_id asc, comment_id asc";
$result = $database->select($sql);
echo json_encode($result);

comment-add.php

<?php
/**
 * This script is to add the comment to database.
 */
use Phppot\DataSource;
require_once __DIR__ . '/DataSource.php';
$database = new DataSource();
$sql = "INSERT INTO tbl_comment(parent_comment_id, comment, comment_sender_name) VALUES (?,?,?)";
$paramType = 'iss';
$paramValue = array(
    $_POST["comment_id"],
    $_POST["comment"],
    $_POST["name"]
);
$result = $database->insert($sql, $paramType, $paramValue);
echo $result;

database.sql

-- phpMyAdmin SQL Dump
-- version 5.1.0
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Jun 30, 2022 at 12:00 PM
-- Server version: 10.4.18-MariaDB
-- PHP Version: 8.0.3

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `comments_system`
--

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

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

CREATE TABLE `tbl_comment` (
  `comment_id` int(11) NOT NULL,
  `parent_comment_id` int(11) DEFAULT NULL,
  `comment` text NOT NULL,
  `comment_sender_name` varchar(200) NOT NULL,
  `comment_at` 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, AUTO_INCREMENT=3;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Download

Comments to “Comments System using PHP and Ajax”

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page