Comment Box system with nested reply using codeigniter and ajax

2019-09-10 Raj Thakur Download Code

Comment Box collects thought from your customers for a particular post and gives you easy to understand the way of think any person about a particular topic. For your customers, it’s a chance to the suggestion for your business that helps to improve the quality of services. In core PHP we are easy to implement comment system but in the Codeigniter framework not easy to create a comment system easy, in which Codeigniter framework their many problems occurs when we call controller for a response. It very easy to insert a comment into the database by using a model but we need current affected row primary key for reply comment without reloading page this problem is solved here.

 

 

Create database tables:

CREATE TABLE `comments` (
  `id` int(11) NOT NULL,
  `user_name` varchar(20) NOT NULL,
  `comments` varchar(20) NOT NULL,
  `createdOn` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `comments_replies` (
  `id` int(11) NOT NULL,
  `comment_id` int(11) NOT NULL,
  `reply` varchar(50) NOT NULL,
  `createdOn` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Database Configuration (Application/config/database.php)

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'commment_system',
	'dbdriver' => 'mysqli',
	'dbprefix' => '',
	'pconnect' => FALSE,
	'db_debug' => (ENVIRONMENT !== 'production'),
	'cache_on' => FALSE,
	'cachedir' => '',
	'char_set' => 'utf8',
	'dbcollat' => 'utf8_general_ci',
	'swap_pre' => '',
	'encrypt' => FALSE,
	'compress' => FALSE,
	'stricton' => FALSE,
	'failover' => array(),
	'save_queries' => TRUE
);

View (Application/views/layout/Com_box.php)

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Solutions Touch</title>
      <?= link_tag('Assets/vendor/bootstrap/css/bootstrap.min.css'); ?>
   <?= link_tag('Assets/prism/prism.css'); ?>
   <?= link_tag('Assets/css/style.css'); ?>
    <link rel="stylesheet" type="text/css" href="Assets/vendor/bootstrap/css/bootstrap.min.css">
   <script src="<?= base_url("Assets/vendor/jquery/jquery.min.js"); ?>"></script>
    <script src="<?= base_url("Assets/vendor/bootstrap/js/bootstrap.bundle.min.js"); ?>"></script>
  </head>
  <body>
    <!-- Navigation -->

<div class="container">
	<div style="margin-top: 20px;">
		<center>
			<h2>Comment Box system with nested reply using codeigniter and ajax</h2>
		</center>
	</div>
	<div style="padding: 50px;">
		<div class="row">
			<div class="col-lg-12">
			 <b><h4 id="comm_count"><?php echo $this->data_model->Count_Comment()+$this->data_model->Count_replies(); ?> Comments </h4></b>
				<textarea class="form-control" rows="3" id="maincomment"></textarea>
				<button class="btn btn-primary" id="addcomment" style="margin: 10px;">Add comment</button>
			</div>
		</div>
		 <div class="row">
	      <div class="col-md-12">
	        <div class="usercomments">
	       	

	        </div>
	      </div>
    	</div>
	    <div class="row replyrow" style="display:none;">
	      <div class="col-md-12" align="right">
	        <textarea align="center" id="replycomment" class="form-control" placeholder="please add comment" cols="30" rows="3" style="margin-top: 10px;"></textarea><br>
	          <button class="btn-default btn" onclick="$('.replyrow').hide();">close</button>
	          <button class="btn-primary btn" onclick="isreply=true;" id="addreply">reply</button>
	      </div>
	    </div>
	</div>
</div>

 </body>
 </html>

JavaScript  code :

<script type="text/javascript">
	$(document).ready(function () {
		var user_name = prompt("Enter your name : ");
		var datetimenow="<?php echo date('Y-m-d'); ?>";

		var max=<?php echo $this->data_model->Count_Comment()+$this->data_model->Count_replies(); ?>; 
		$("#addcomment").on('click', function () {
			var mainComment=$("#maincomment").val();  
			
			//if want show comment particular post and blog,declare post id and provide primary key 
 
			if (mainComment.length>=1) {
				$.ajax({
					url: "<?php echo base_url() ?>com/addcomment",
					method: 'POST',
					datatype: 'text',
					data: {
					mainComment: mainComment,
					user_name:user_name
					},
					success:function (data) {
						var result = JSON.parse(data);
						$("#maincomment").val("");
						max++;
						$("#comm_count").text(max+" Comments");
						
						$(".usercomments").prepend('<div class="comment"><div class="user">'+user_name+' <span class="time">'+datetimenow+'</span></div><div class="usercomment">'+mainComment+'</div> <div class="reply"><a href="javascript:void(0)" data-commentID="'+result.id+'" onclick="reply(this)">REPLY</a></div> <div class="replies"></div> </div>');
					},
					error: function(){
						alert('Data not inserted.');
					}

				});
			}
			else{
				alert('please check your commment box.');
			}
      
		});



  $("#addreply").on('click', function () {
      // body...
      var replycomment=$("#replycomment").val();    
      
      if (replycomment.length>=1) {
        $.ajax({
          url: "<?php echo base_url() ?>com/addreply",
          method: 'POST',
          datatype: 'text',
          data: {
            replycomment: replycomment,
            commentid:commentid
          },
          success:function (response) {
               max++;
              $("#comm_count").text(max +" Comments");
              $("#replycomment").val("");
              
              $(".replyrow").hide();
         
              $(".replyrow").parent().next().append('<div class="comment">'+replycomment+'</div>'); 
            },
          error: function(){
            alert('Data not inserted');
          }

        });
      }
      else{
        alert('please check your input reply commment');
      }
    
    });    



		
		getallComment(0,max);

	});




	function reply(caller)
  {
    commentid=$(caller).attr('data-commentID');
    $(".replyrow").insertAfter($(caller));
    $(".replyrow").show();
  }

    
    function getallComment(start,max)
  {

    if (start> max) {
      return;
    }
    $.ajax({
          url: '<?php echo base_url() ?>com/allComment',
          method: 'POST',
          datatype: 'JSON',
          data: {
            start: start
          },
          success:function (response) {
            // body...
            var d = $.parseJSON(response);
            $(".usercomments").append(d);
            getallComment((start+20),max);
          },
          error: function () {
            // body...
            alert('Data not found');
          }
    });
  }



</script>

Controllers (Application/controllers/com.php)

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class com extends CI_Controller {

	public function index()
	{
		$this->load->view('layout/Com_box');
	}


		public function addcomment()
	{
		# code...
		$result= $this->data_model->addcomment();
		if ($result) {
			# code...
			$user_id = $this->input->post('user_name'); 
	 		$comment = $this->input->post('mainComment'); 
	 		$letasrow=$this->data_model->affected_comment($user_id,$comment);
 			if ($letasrow) {
 				# code...
 				echo json_encode($letasrow);
 			}


		}
		return true;
 		
	}


		public function addreply()
	{
		# code...
		$result= $this->data_model->addreply();
			


		return true;
 		
	}


		public function allComment()
	{
		# code...
 	$response='';
 	$response1='';
	$result= $this->data_model->allComment();
      foreach ($result as  $value) {
        # code...
 $result1= $this->data_model->comment_replies($value->id);
      if ($result1) {
      	# code...
			foreach ($result1 as  $value1) {
			# code...
				$response1.= '<div class="comment">
				
				<div class="usercomment">'.$value1->reply.'</div>
				</div>';                       
			}
	}

      		$response.= '<div class="comment">
						<div class="user">'.$value->user_name.'<span class="time"> '.date("Y-m-d", strtotime($value->createdOn)).'</span></div>
						<div class="usercomment">'.$value->comments.'</div>
						
						<div class="reply"><a href="javascript:void(0)" data-commentID='.$value->id.' onclick="reply(this)">REPLY</a></div>						
						<div class="replies">'.$response1.'</div>					
					</div>';                       
         	$response1='';

        }
		echo json_encode($response);
	}


}

Models (Application/models/data_model.php)

<?php
class data_model extends CI_Model
{	

			public function addcomment()
 	{

 		date_default_timezone_set('Asia/Kolkata');
 		$field  = array('user_name' => $this->input->post('user_name'), 
 						'comments' => $this->input->post('mainComment'), 
 					'createdOn'=>date('Y-m-d H:i:s')
 			);
 		$this->db->insert('comments', $field);
 		if ($this->db->affected_rows() >0) {
 			# code...
 			return true;
 		}
 		else{
 			return false;
 		}

 	}



 		public function comment_replies($cid)
 	{
 		# code...
 		$query= $this->db->select('')
 						->from('comments_replies')
 						->where('comments_replies.comment_id',$cid)
 						->get();
 		if ($query->num_rows()>0) {
 			# code...
 			return $query->result();
 		}
 		else{
 				return false;
 		}
 	}


public function affected_comment($uid,$comment)
	{

		 $one_post=$this->db->select()
							->from('comments')
							->where('comments.user_name',$uid)
							->where('comments.comments',$comment)
							->order_by('comments.id','DESC')
							->limit(1)
							->get();
		   return $one_post->row();	
	}



	public function Count_Comment()
	{
		$all_users=$this->db->select()
						    ->get('comments');
		return $all_users->num_rows();
	}

	public function Count_replies()
	{
		$all_users=$this->db->select()
						    ->get('comments_replies');
		return $all_users->num_rows();
	}

 		public function addreply()
 	{
 		# code...
 		date_default_timezone_set('Asia/Kolkata');

 		$field  = array('comment_id' => $this->input->post('commentid'), 
 						'reply' => $this->input->post('replycomment'), 
 						'createdOn'=>date('Y-m-d H:i:s')
 			);
 		$this->db->insert('comments_replies', $field);
 		if ($this->db->affected_rows() >0) {
 			# code...
 			return true;
 		}
 		else{
 			return false;
 		}

 	}



 		public function allComment()
	{
		$all_users=$this->db->select('')
							->from('comments')
						    ->order_by('id', 'DESC')
						    ->get();
		return $all_users->result();
	}



}
?>

About author

Card image cap
Raj Thakur

I’m a full-stack developer, with a strong programming experience on web base frameworks.!

-PHP developer

0 Comments