Trong bài này mình sẽ hướng dẫn về phần tạo ô bình luận cho website bằng PHP + Ajax. Hệ thống bình luận này bao gồm các tính năng để thêm trả lời cho bất kỳ nhận xét nào do người dùng thêm.Mình đã sử dụng jQuery AJAX để thêm nhận xét / trả lời vào cơ sở dữ liệu và hiển thị chúng cho người dùng. Vì nó sử dụng AJAX, nó sẽ mang lại trải nghiệm liền mạch cho người dùng. Mỗi nhận xét sẽ có một id duy nhất và id này sẽ được sử dụng để tham chiếu phần tử HTML hiển thị nhận xét. Id nhận xét này sẽ được chuyển đến  AJAX để thực hiện các hoạt động định hướng nhận xét như thêm trả lời. Trong một hướng dẫn trước, chúng ta đã thấy cách đọc và ghi vào cơ sở dữ liệu thông qua một cuộc gọi AJAX.

Code HTML để hiển thị nhận xét

 HTML để nhập tên và nhận xét / trả lời sẽ được xuất bản. Khi gửi nhận xét của người dùng,  AJAX sẽ được gọi để thêm dữ liệu vào cơ sở dữ liệu. Mã AJAX sẽ thêm hoặc thêm vào bình luận / trả lời được đăng bởi người dùng sau khi các hoạt động AJAX thành công. Các chú thích và các câu trả lời được thêm vào trong một khung nhìn cấu trúc như là một phần tử cha-con( Giống như bạn trả lời bình luận của một ai đó trên facebook . Mỗi nhận xét được hiển thị bằng cách sử dụng phần tử cha có chứa danh sách các phần tử con hiển thị các câu trả lời của nó.

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

Và mình sẽ có 2 file : 1 file insert vào cơ sở dữ liệu và 1 file lấy các bình luận ra ngoài như sau :

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;
?>

Code demo cho chương trình : Tại đây

Chào các bạn mình là Quốc Hùng , mình sinh ra thuộc cung song tử ,song tử luôn khẳng định chính mình ,luôn luôn phấn đấu vượt lên phía trước ,mình sinh ra và lớn lên tại vùng đất võ cổ truyền ,đam mê của mình là coder ,ngày đi học tối về viết blog ...