Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to post a comment on blog using Ajax?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 2
    • 0
    • 3.21k
    Comment on it

    Hello Reader's , If you have developed the blogging website and you want to make commenting via ajax then this article will be very helpful for you. You can develop commenting function with many ways but if you use ajax then you can speed up your website. So let's get started working on developing it.

    Step1: Create an HTML form which will show the blog content and its photos. Its code will go like this:-

    <div>	
    			
    	<b><?php echo $viewblog['title'];?></b><br>
    	<span ><img src="<?php echo base_url().'assets/blog_images/'.$viewblog['photo'];?>" class= "blog_full"></span><br>
    	<p class="viewBlogs"><?php echo $viewblog['content'];?><br><br>
    	<b>By:-</b> <?php echo $viewblog['first_name']." ".$viewblog['last_name'];?></p>
    	<b>Posted Date:-</b> <?php   echo date("D d M Y h:i a",strtotime( $viewblog['modified'])); ?></p>
    	<br>
    
    </div>
    
    <br><br>
    <ul id ="show_comments"></ul><br>
    	<?php $showForm = 0;
    		if( isset($this->session->userdata['userdata']) && !empty( $this->session->userdata['userdata'] ) )
    			{
    				if($this->session->userdata['userdata']['id'] == $viewblog['user_id'])
    					{
    						echo "This is your blog";
    					}else{ $showForm = 1;?>
    							<div>
    								<form>									
    									<textarea id = "write_comment" placeholder = "Write your comment here..." cols="85" rows="5"></textarea><br>
    									<button type="button" id="comment_post" class="btn btn-success" disabled>Post Comment</button>
    								</form>	
    							</div>
    											
    							<?php } 
    			}else{ ?>
    			<a href="<?php echo base_url();?>user/redirectLogin/"  class="btn btn-warning blueBTN" >Login to comment</a>
    			<?php } ?>

    In the code above we have printed the blog and it's content with the image (if provided). There is text area box at the bottom of the page. On typing the comment inside it the button for posting the comment will activate. Any comment typed inside this text area will be stored in DB and append in the previous comment via ajax.

     

    Step 2: Now to make the functionality of ajax, we will be using some part of javascript. And it's code will go like this:-

    <script type="text/javascript">
    // this part of ajax is fetching the comments 
    	$( document ).ready(function()
    	{
    		var blog_id = '<?php echo $viewblog['id']?>';
    
    				$.ajax({
    						type: "POST",
    						url: webUrl+'blog/fetchBlogComments',
    						data: ({blog_id : blog_id}),   
    						success: function(data) {
    						$("#show_comments").html(data);
    					}
    				});
    	});
    
    $("#write_comment").keyup(function(){
    	if($('#write_comment').val().length > 1)
    		{
    			$('#comment_post').prop("disabled", false);
    		}else{
    			$('#comment_post').prop("disabled", true);
    		}
    
    		});
    </script>
    
    	<?php if($showForm == '1'){//user is logged in, now showing the comment box form?>
    		<script type="text/javascript">
    		  $("#comment_post").click(function(){
    				var comment = $("#write_comment").val();
    				var blog_id = '<?php echo $viewblog['id']?>';
    				var user_id = '<?php echo $this->session->userdata["userdata"]["id"];?>';
    				var username = '<?php echo $this->session->userdata['userdata']['first_name'].' '.$this->session->userdata['userdata']['last_name']?>';
    					$.ajax({
    						type: "POST",
    						url: webUrl+'user/postComment',
    						data: ({comment: comment, blog_id : blog_id, user_id: user_id }),   
    						success: function(data)
    							{       
    							 if(data == 'posted') 
    							 	{
    							 		$("#show_comments").append('<li>'+comment+' By :-'+username+'</li>').fadeIn(3000);
    							 	}
    							}
    						});
    					});
    		</script>	
    
    	<?php } ?>

     

    Step 3: In the above javascript code the ajax is using the request to fetch the previous comments and post new ones. But to save and insert into DB you need to make function in controller and this will go like this:-

    //function for getting the post data of comment by user
    	public function postComment()
    		{
    			extract($this->input->post());
    			$postComment['user_id'] = trim($comment);
    			$postComment['blog_id'] = trim($blog_id);
    			$postComment['user_id'] = trim($user_id);			
    			$postComment['comment'] = trim($comment);			
    			$postComment['modified'] = $postComment['created']  = date('Y-m-d H:i:s');
    			if($this->db->insert('comments', $postComment) )
    				{
    					echo 'posted';
    				}else{
    					echo 'failure';
    				}
    		}
    
    	//fetch the comments on a blog. This uses ajax 
    	public function fetchBlogComments(){
    
    		$this->db->select('comments.id, comments.user_id, comments.modified, comment, users.first_name, users.last_name');
    		$this->db->from('comments');
    		$this->db->join('users','users.id = comments.user_id');
    		$this->db->where('comments.blog_id', $this->input->post('blog_id'));
    		$this->db->where('comments.deleted', '0');
    		$this->db->where('comments.status', '1');
    		$comments = $this->db->get()->result_array();
    		$html = "";
    		foreach ($comments as $comment) {
    			$html .= '<li>'.$comment['comment'].' By :-'.$comment['first_name'].' '.$comment['last_name'].'</li>';
    		}
    			echo "<pre>";print_r($html);echo "</prE>";
    	}

    Now when you load this code. This will generate the page of a blog and a text box will appear for writing the comments. As user click the comment button his comment will get auto-saved into DB and append into the above codes. The output of the code will be as shown in the screenshot as below

     

     

    How to post a comment on blog using Ajax?

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: