Comments System using PHP and Ajax

Last modified on October 2nd, 2018 by Vincy.

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 comment added by the user. I 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.

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.

people-comments

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.

<div class="comment-form-container">
    <form id="frm-comment">
        <div class="input-row">
            <input type="hidden" name="comment_id" id="commentId"
                placeholder="Name" /> <input class="input-field"
                type="text" name="name" id="name" placeholder="Name" />
        </div>
        <div class="input-row">
            <textarea class="input-field" type="text" name="comment"
                id="comment" placeholder="Add a Comment">  </textarea>
        </div>
        <div>
            <input type="button" class="btn-submit" id="submitButton"
                value="Publish" />
            <div id="comment-message">Comments 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='commet-row-label'>from</span> <span class='posted-by'>"
											+ data[i]['comment_sender_name']
											+ " </span> <span class='commet-row-label'>at</span> <span class='posted-at'>"
											+ data[i]['date']
											+ "</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='commet-row-label'>from</span> <span class='posted-by'>"
						+ data[i]['comment_sender_name']
						+ " </span> <span class='commet-row-label'>at</span> <span class='posted-at'>"
						+ data[i]['date'] + "</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>

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. 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.

comment-list.php

<?php
require_once ("db.php");

$sql = "SELECT * FROM tbl_comment ORDER BY parent_comment_id asc, comment_id asc";

$result = mysqli_query($conn, $sql);
$record_set = array();
while ($row = mysqli_fetch_assoc($result)) {
    array_push($record_set, $row);
}
mysqli_free_result($result);

mysqli_close($conn);
echo json_encode($record_set);
?>

comment-add.php

<?php
require_once ("db.php");
$commentId = isset($_POST['comment_id']) ? $_POST['comment_id'] : "";
$comment = isset($_POST['comment']) ? $_POST['comment'] : "";
$commentSenderName = isset($_POST['name']) ? $_POST['name'] : "";
$date = date('Y-m-d H:i:s');

$sql = "INSERT INTO tbl_comment(parent_comment_id,comment,comment_sender_name,date) VALUES ('" . $commentId . "','" . $comment . "','" . $commentSenderName . "','" . $date . "')";

$result = mysqli_query($conn, $sql);

if (! $result) {
    $result = mysqli_error($conn);
}
echo $result;
?>

PHP AJAX Comment System – Output

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

comment-system-output

Download

This PHP code tutorial was published on December 18, 2017.

↑ Back to Top

Share this Article