How to Add Dynamic Comments Without Page Reload Using PHP and jQuery
6 min read
Comments are an important feature in modern websites to encourage user interaction. However, reloading the page every time a comment is submitted can reduce user experience. The solution is creating a dynamic comment system without page reload using PHP and jQuery.
This article explains how to build a simple comment system that:
- Submits comments without reloading
- Displays new comments instantly
- Is beginner-friendly
- Uses no complex frameworks
Basic Concept of Dynamic Comments
The workflow is:
- User writes a comment
- jQuery sends data using AJAX
- PHP saves the comment to the database
- PHP returns updated comments
- Page updates without reload
This technique is known as an AJAX-based comment system.
Why PHP and jQuery?
Because:
- PHP is widely supported
- jQuery AJAX is simple and concise
- Works well on shared hosting
- Lightweight and stable
This approach fits blogs, company websites, and small news portals.
Simple Database Structure
CREATE TABLE comments (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
comment TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
File Structure
index.php
submit_comment.php
fetch_comments.php
1. HTML Page (index.php)
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Comments</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h3>Write a Comment</h3>
<input type="text" id="name" placeholder="Name"><br><br>
<textarea id="comment" placeholder="Comment"></textarea><br><br>
<button id="send">Submit</button>
<hr>
<h3>Comments</h3>
<div id="comment-box"></div>
<script>
$(document).ready(function(){
function loadComments() {
$.get("fetch_comments.php", function(data){
$("#comment-box").html(data);
});
}
loadComments();
$("#send").click(function(){
$.post("submit_comment.php", {
name: $("#name").val(),
comment: $("#comment").val()
}, function(){
$("#comment").val("");
loadComments();
});
});
});
</script>
</body>
</html>
2. PHP to Save Comments (submit_comment.php)
<?php
$conn = mysqli_connect("localhost","root","","test_db");
$name = $_POST['name'];
$comment = $_POST['comment'];
mysqli_query($conn,
"INSERT INTO comments (name, comment) VALUES ('$name','$comment')"
);
3. PHP to Fetch Comments (fetch_comments.php)
<?php
$conn = mysqli_connect("localhost","root","","test_db");
$result = mysqli_query($conn,
"SELECT * FROM comments ORDER BY id DESC"
);
while($row = mysqli_fetch_assoc($result)) {
echo "<p><strong>".$row['name']."</strong><br>";
echo $row['comment']."</p><hr>";
}
Result
- Comments appear instantly
- No page reload required
- Better user experience
- Easy to extend
Conclusion
Creating dynamic comments without page reload using PHP and jQuery is a simple yet powerful way to enhance user interaction. AJAX allows websites to feel more responsive and modern without complicated technologies.