Top

Follow me and receive all the latest free scripts:

By Email:

Categories
Most Popular Posts

jQuery comment system tutorial

jQuery comment system tutorial

Published September 22, 2014 by , category jQuery

jqueryphphtmlmysql

How to create a comment system using jQuery, Ajax and PHP

Introduction

In this tutorial I will explain you how to create a simple comment system using jQuery, Ajax and PHP. A comment system is useful to keep interaction between you, your content and members of your website. I also use this system on this website. As usually you can easily adapt it to your website and add features: photo member etc.

This fully working code sample features:

Files architecture

index.php
database_connection.php

ajax

tuto_blogcommentajax.php

js

tuto_comments.js

jquery

jquery-1.10.1.min.js

Live demo

Here is a live demo, you can see another running version below (this website comment system).

For safety reasons and to prevent misuse, datas are not inserted in the database

Comments

My Name Posted on 2014-09-22
I post a comment just to test :)

Leave a comment

Database structure sample

This database structure sample include fields such as page_id, com_name, com_email and com_text from the poster. Feel free to add more fields if you need.

page_id is the id (database row number) of the page where you place the comment system.

CREATE TABLE IF NOT EXISTS `tc_tuto_comments` (
  `id` int(6) NOT NULL AUTO_INCREMENT,
  `page_id` int(6) NOT NULL,
  `com_name` varchar(50) NOT NULL,
  `com_email` varchar(50) NOT NULL,
  `com_text` text NOT NULL,
  `date_ins` date NOT NULL DEFAULT '0000-00-00',
  `hour_ins` time NOT NULL DEFAULT '00:00:00',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 ;

HTML/PHP code

I don't include the file database_connection.php where you find the database connection parameters. You must already have it. Name the page as you want, index.php in my case, if I follow the files architecture.

If you need, I wrote a tutorial about how to connect database using Object-Oriented, PHP and MySQL, the kind of connection I use for this website.

<?PHP
// File index.php
include('database_connection.php'); //your database connection
$bdd = new db(); //your database connection
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr">
<head>
	<title>Comment system</title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css" type="text/css"> <!-- I use Bootstrap for the CSS -->
	<script type="text/javascript" src="jquery/jquery-1.10.1.min.js"></script> <!-- path to jQuery -->
	<script type="text/javascript" src="js/comments.js"></script> <!-- path to tuto_comments.js -->
</head>

<body>
	
<div class="container">
	<div class="row">
	  <div class="col-md-12">
		Header
	  </div>
	</div>	
</div>
	
<div class="container">
	<div class="row">
		<div class="col-md-12">
			<?php
			$blobCom = $bdd->getAll('SELECT * FROM tc_tuto_comments WHERE page_id=1 ORDER BY date_ins DESC, hour_ins DESC'); // get old comments from database // page_id is the id of your current page. Replace by the correct id.
			$nbrCom = count($blobCom); // number of comments returned
			
			echo '<h2>Comments</h2>';
			
			if ($nbrCom == 0) { // if 0 comment
				echo '<b>No comments for the moment!</b>';
			} else { // if at least 1 comment we display them
				foreach($blobCom as $blobCom) {
					echo '<b>'.$blobCom['com_name'].'</b> <small class="text-muted">Posted on '.$blobCom['date_ins'].'</small>';
					echo '<br />';
					echo nl2br($blobCom['com_text']);
					echo '<hr></hr>';
				}
			}
			?>
		
			<h2>Leave a comment</h2>
								
			<div id="newComment"></div> <!-- the comment posted will be displayed here -->
			
			<form class="form-horizontal" role="form" action="#" method="post">
				<input type="hidden" id="page_id" value="1"/> <!-- hidden field to pass the variable page_id. I put the value at 1, so I consider it's the page number 1 -->
				<!-- If you add the comment system in a large number of page, you must replace 1 by a variable such as $page_id -->
				
				<div class="form-group" id="formGroupName">
					<label class="col-md-2 control-label">Your Name</label>
					<div class="col-md-4">
						<input type="text" name="com_name" id="com_name" class="form-control" />
						<span class="help-block"></span>
					</div>
				</div>
				
				<div class="form-group" id="formGroupEmail">
					<label class="col-md-2 control-label">Your Email</label>
					<div class="col-md-4">
						<input type="text" name="com_email" id="com_email" class="form-control" />
						<span class="help-block"></span>
					</div>
				</div>
				
				<div class="form-group" id="formGroupText">
					<label class="col-md-2 control-label">Your Comment</label>
					<div class="col-md-10">
					<span class="help-block"></span>
					<textarea class="form-control" rows="8" id="com_text" name="com_text"></textarea>
					</div>
				</div>
				
				<p align="center"><input type="submit" class="submitComment btn btn-primary" value="Submit Comment" /></p>
			</form>
								
		</div>
	</div>
</div>

</body>
</html>

jQuery code

// File js/tuto_comments.js
$(function() {
	//a function checking the validity of an email
	function validEmail(email) {
		var r = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
		return (email.match(r) == null) ? false : true;
	}
	
	$(".submitComment").click(function() {
		var com_name = $('#com_name').val(); // get name from comment name field
		var com_email = $('#com_email').val(); // get email from comment email field
		var com_text = $('#com_text').val(); // get text from comment text field
		var page_id = $('#page_id').val(); // get the page id from the hidden page_id field
		var dataFields = {'com_name': com_name, 'com_email': com_email, 'com_text': com_text, 'page_id': page_id}; // prepare datas string
		
		var checkName = $('#com_name').val().length; // get the length of the name field
		var checkEmail = validEmail(com_email); // check the email format with the above function validEmail()
		if(checkName < 3 || checkEmail == false || com_text=='') { // name must be at least 4 characters, email must be valid and text not empty (you may change all that)
			if (checkName < 3) { // if name below 4 characters
				$('#formGroupName').attr('class', 'form-group has-error'); // this is a Bootstrap CSS, I add has-error to the class so the field will turn red 
				$('#formGroupName span').text('minimum 4 characters'); // I add a help text in the <span> node
			} else {
				$('#formGroupName').attr('class', 'form-group has-success'); // this is a Bootstrap CSS, I add has-success to the class so the field will turn green 
				$('#formGroupName span').text(''); // remove help text in the <span> node
			}
			if (checkEmail == false) { // if email not valid
				$('#formGroupEmail').attr('class', 'form-group has-error'); // this is a Bootstrap CSS, I add has-error to the class so the field will turn red 
				$('#formGroupEmail span').text('wrong email format'); // I add a help text in the <span> node
			} else {
				$('#formGroupEmail').attr('class', 'form-group has-success'); // this is a Bootstrap CSS, I add has-success to the class so the field will turn green 
				$('#formGroupEmail span').text(''); // remove help text in the <span> node
			}
			if (com_text=='') {
				$('#formGroupText').attr('class', 'form-group has-error'); // this is a Bootstrap CSS, I add has-error to the class so the field will turn red 
				$('#formGroupText span').text('This field can\'t be empty'); // I add a help text in the <span> node
			} else {
				$('#formGroupText').attr('class', 'form-group has-success'); // this is a Bootstrap CSS, I add has-success to the class so the field will turn green 
				$('#formGroupText span').text(''); // remove help text in the <span> node
			}
		} else { // if everything valid
			$('#newComment').html('<img src="design/loader.gif" /> Processing...'); // loader image apprears in the <div id="newComment"></div>
			$.ajax({
				type: "POST",
				url: "ajax/tuto_blogcommentajax.php", // call the php file ajax/tuto_blogcommentajax.php to insert new datas in the database
				data: dataFields, // send dataFields var
				timeout: 3000,
				success: function(dataBack){ // if success
					$('#newComment').html(dataBack); // return new datas and insert in the <div id="newComment"></div>
					$('#com_text').val(''); // clear the com_text field // I don't clear the name and email field if the guy wants to post another comment
					},
				error: function() { // if error
					$('#newComment').text('Problem!'); // display "Problem!" in the <div id="newComment"></div>
				}
			});
		}
		return false;
	});
});

PHP code

Ajax call for database update

// File ajax/tuto_blogcommentajax.php
<?php
include('../database_connection.php'); // database access
$bdd = new db(); // database access

if($_POST)
{
$com_name = strip_tags($_POST['com_name']); // get name
$com_email = strip_tags($_POST['com_email']); // get email
$com_text = strip_tags($_POST['com_text']);  // get text
$page_id = $_POST['page_id'];  // get the id of the current page

$insertCom = $bdd->execute('INSERT INTO tc_tuto_comments (com_name, com_email, com_text, page_id, date_ins, hour_ins) VALUE ("'.$com_name.'", "'.$com_email.'", "'.$com_text.'", '.$page_id.', NOW(), NOW())'); // insert datas in the database
}

echo '<div class="well well-sm">'; // returm the new comment
echo "<b>$com_name</b> <small class='muted'>posted just now</small>";
echo "<br />";
echo nl2br($_POST['com_text']);
echo '</div>';
?>

About Simon Laroche
Simon Laroche on Google+
Simon Laroche on Twitter
Simon Laroche on Facebook
Simon Laroche on Pinterest
Simon Laroche on LinkedIn
: I am a Coder, Designer, Webmaster and Expert SEO Consulting, I'm also a wise traveller and an avid amateur photographer. I created the website TipoCode and many others such as Landolia: a World of Photos...

If you need help about this script, please leave a comment below. I reply as much as I can depending of my time, you may also get help from others.
I also offer a paid support, if you are in the need to adapt or create a script...

Leave a comment

Comments (18 comments)

lait Posted on May 25, 2017
nice
taking a look Posted on March 25, 2017
I wonder if I can make this work for my site...
Tim Posted on March 18, 2017
This is for testing purpose.
Asss Posted on January 07, 2017
Nice!
shamz Posted on November 19, 2016
nice
lavy Posted on September 14, 2016
nice
rey Posted on May 30, 2016
nice
demo Posted on April 15, 2016
Good tutorial...
Aldegunde Posted on April 09, 2016
Hi Simon, thanks a lot for this code,

I´m playing with it as learnign exercise and parctice, I found out a problem that I can not solve by my self, :(. So I decide contact you looking for help.

I want to show comments but just the one linked with one tasks page, so I modify the SQL to this one:

'SELECT * FROM comments
LEFT JOIN tasks ON comments.page_id = tasks.t_id
WHERE page_id = t_id ORDER BY date_ins DESC, hour_ins DESC');

So now individual page shows only the comments linked with it.

I changed following you indications this part of the form:
<input type="hidden" id="page_id" value="$t_id"/>

Where t_id is the individual page for taks so I have an task page and all comments linked with it.

The problem comes when trying to save it as indefined index and multiple errors from tuto_blogcommentajax.php

Could you help me on that? I appreciate to much you help for a php beginer.

BR


boubs Posted on April 01, 2016
Cool ;)
mac Posted on March 31, 2016
good
iamblest Posted on September 01, 2015
nice one
wfwe Posted on August 15, 2015
Nice
brad Posted on August 14, 2015
br comment
test Posted on August 09, 2015
nice tuts....! thanks
guy Posted on March 17, 2015
Thanks
carl Posted on February 14, 2015
thanks bro.. :0
John Posted on January 19, 2015
Thanks!