Ajax Comments Script Tutorial

In this post I will explain (line by line commentary code) how to make an ajax comments script that insert the comments data using ajax (jquery,php and mysql).

database sql code ajax_comments.sql











CREATE TABLE IF NOT EXISTS `comments` (
  `comment_id` int(12) NOT NULL AUTO_INCREMENT,
  `post_id` int(12) NOT NULL,
  `name` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `comment` text NOT NULL,
  `datetime` int(12) NOT NULL,
  PRIMARY KEY (`comment_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

index file index.php























// after connecting to database
// we have to retrive the existing comments from database
$query = mysql_query("SELECT * FROM comments WHERE post_id='$post_id' ORDER BY comment_id ASC"); // comments query
$check = mysql_num_rows($query); // comments number
if ($check > 0) { // if comments number is great than 0
while ($row = mysql_fetch_array($query)) { // fetch the comments table from database as array
// comments display code
echo '<div class="comment">
<img src="http://www.gravatar.com/avatar/'.md5(strtolower(trim($row['email'] 
))).'?s=50&d=mm&r=pg">
<div class="comment_info"><span class="sender">By : '.$row['name'] .'</span><span class="datetime">'.date('j-n-Y h:i a',$row['datetime'] 
).'</span></div>
<p>'.nl2br($row['comment'] 


).'</p>
</div>';
}
}

add comment form index.php












<div id="comment_display"></div><!-- here displayed the new comment -->
<form method="POST" id="commentform">
<label>Name</label>
<input name="name" id="name" type="text">
<label>E-Mail</label>
<input name="email" id="email" type="text">
<label>Comment</label>
<textarea name="comment" id="comment" rows="4"></textarea>
<input id="comment_btn" name="submit" value="Add Comment" type="button">
</form>

JQuery functions functions.js















































// function to validate email      
function validateEmail(email) {
var re = /^(([^<>()[] .,;:s@"]+(.[^<>()[] .,;:s@"]+)*)|(".+"))@(([[0-9] {1,3}.[0-9] {1,3}.[0-9] {1,3}.[0-9] {1,3}])|(([a-zA-Z-0-9] +.)+[a-zA-Z] 








































{2,}))$/;
    return re.test(email);
}
 
// comment submit function
$(function() {
$("#comment_btn").click(function() {
var comment = $("textarea#comment").val(); // define the comment variable
var name = $("input#name").val(); // define the name variable
var email = $("input#email").val(); // define the email variable
if (name == '') // if name field is empty
{
alert("Write Your Name Please."); // alert an error mesaage
}
else if(email=='') // if email field is empty
{
alert("Write Your Email Please."); // alert an error mesaage
}
else if(!validateEmail(email)) // if email is invalid
{
alert("Write Valid Email Please."); // alert an error mesaage
}
else if(comment=='') // if comment textarea field is empty
{
alert("Write The Comment Please."); // alert an error mesaage
}
else
{
$.ajax({ // JQuery ajax function
type: "POST", // ajax submit method
url: "add_comment.php", // php file that will recieve the data and process it
data: 'name='+ name +'&email='+ email +'&comment='+ comment, // data sent to php file
cache: false,
success: function(html){ // if the result returns success
$("#comment_display").after(html); // display the new comment in the <div id="comment_display"></div>
 document.getElementById('commentform').reset(); // reset the form
} 
});
}
return false;
});
});

PHP processor file add_comment.php





























$post_id = 1; // you can change it or retrive it from database
 
if (isset($_POST)) { // if the post request is sent
// sanitize the submitted variables
$name = htmlspecialchars(trim(mysql_real_escape_string(strip_tags($_POST['name'] 
))), ENT_QUOTES);
$email = htmlspecialchars(trim(mysql_real_escape_string(strip_tags($_POST['email'] 
))), ENT_QUOTES);
$comment = htmlspecialchars(trim(mysql_real_escape_string(strip_tags($_POST['comment'] 










))), ENT_QUOTES);
// check if the submitted variables not empty
if (!empty($name) OR !empty($mail) OR !empty($comment)) {
$datetime = time(); // the time in unix timestamp formula
$insert = mysql_query("INSERT INTO comments (post_id,name,email,comment,datetime) VALUES ('$post_id','$name','$email','$comment','$datetime')"); // inserting the comment to database
if ($insert) { // if the comment is inserted to database
$new_comment_id = mysql_insert_id(); // the id of the last inserted comment
$query = mysql_query("SELECT * FROM comments WHERE comment_id='$new_comment_id' AND post_id='$post_id'"); // retrive the last inserted comment from database
$row = mysql_fetch_array($query); // fetch the comment rows to array
// display the comment
echo '<div class="comment">
<img src="http://www.gravatar.com/avatar/'.md5(strtolower(trim($row['email'] 
))).'?s=50&d=mm&r=pg">
<div class="comment_info"><span class="sender">By : '.$row['name'] .'</span><span class="datetime">'.date('j-n-Y h:i a',$row['datetime'] 
).'</span></div>
<p>'.nl2br($row['comment'] 



).'</p>
</div>';
}
}
}
Download Tutorial Files

Leave a Comment

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