Skip to main content

Live Comment System with jQuery Ajax PHP and MySQL

Recently I have been made a post that focused on how to submit form without page refreshing. That post shows the basic functionality of using jQuery Ajax. On the same follow this post will describe how we can create a comment system to post an instant comment without page refreshing. Let's start...


Demo Download Source
Database Design
We need to create two database table post and comment.

Post Table
The post table holds post data like post id, title, body or whatever you want. You need to inset some table rows. You will find it on demo.sql file.
CREATE TABLE `post` (
  `post_id` int(8) NOT NULL AUTO_INCREMENT,
  `post_title` varchar(124) NOT NULL,
  `post_body` text NOT NULL,
  PRIMARY KEY (`post_id`)
);
Comment Table
The comment table holds comment information. Here I only store commenter's name, mail and comment. If you want you can store more information like ip address, url or whatever you. Another thing you must to do, that to include is post id. It will tell you this comment is for which post.
CREATE TABLE `comment` (
  `id` int(8) NOT NULL AUTO_INCREMENT,
  `name` varchar(128) NOT NULL,
  `mail` varchar(128) NOT NULL,
  `comment` text NOT NULL,
  `post_id` int(8) NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
);
HTML Markup
This html code holds simple single post information. Post data will be placed in div.post and comments will be place in div.comment-block. We also need to add a comment form. I used here some html5 form properties, attributes and form validations like type="email", placeholder and required.
<html>
<head>
  <title>Comment System</title>
<head>
<body>
  <div class="post">
    <!-- post will be placed here from db -->
  </div>
  <div class="comment-block">
    <!-- comment will be apped here from db-->
  </div>
  <!-- comment form -->
  <form id="form" method="post">
    <!-- need to supply post id with hidden fild -->
    <input type="hidden" name="postid" value="1">
    <label>
      <span>Name *</span>
      <input type="text" name="name" id="comment-name" placeholder="Your name here...." required>
    </label>
    <label>
      <span>Email *</span>
      <input type="email" name="mail" id="comment-mail" placeholder="Your mail here...." required>
    </label>
    <label>
      <span>Your comment *</span>
      <textarea name="comment" id="comment" cols="30" rows="10" placeholder="Type your comment here...." required></textarea>
    </label>
    <input type="submit" id="submit" value="Submit Comment">
  </form>
</body>
</html>
JavaScript Code
This jQuery code is based on jQuery form submit event. When form submitted by user it sends a asynchronous request using jQuery.ajax method.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
  var form = $('form');
  var submit = $('#submit');

  form.on('submit', function(e) {
    // prevent default action
    e.preventDefault();
    // send ajax request
    $.ajax({
      url: 'ajax_comment.php',
      type: 'POST',
      cache: false,
      data: form.serialize(), //form serizlize data
      beforeSend: function(){
        // change submit button value text and disabled it
        submit.val('Submitting...').attr('disabled', 'disabled');
      },
      success: function(data){
        // Append with fadeIn see http://stackoverflow.com/a/978731
        var item = $(data).hide().fadeIn(800);
        $('.comment-block').append(item);

        // reset form and button
        form.trigger('reset');
        submit.val('Submit Comment').removeAttr('disabled');
      },
      error: function(e){
        alert(e);
      }
    });
  });
});
</script>
PHP Code
ajax_comment.php file holds this code. When the JavaScript sends asynchronous request this file receives serialized data and inserts into comment table. It also print out new comment for Ajax callback. Note, I haven't used any form validation code here. If you want to use it in real life project you must need to add form validation code.
<?php
// code will run if request through ajax
if (isset( $_SERVER['HTTP_X_REQUESTED_WITH'] )):
  include('config.php');
  include('function.php');
  // connecting to db
  dbConnect();
  
  if (!empty($_POST['name']) AND !empty($_POST['mail']) AND !empty($_POST['comment']) AND !empty($_POST['postid'])) {
    // preventing sql injection
    $name = mysql_real_escape_string($_POST['name']);
    $mail = mysql_real_escape_string($_POST['mail']);
    $comment = mysql_real_escape_string($_POST['comment']);
    $postId = mysql_real_escape_string($_POST['postid']);

    // insert new comment into comment table
    mysql_query("
      INSERT INTO comment
      (name, mail, comment, post_id)
      VALUES('{$name}', '{$mail}', '{$comment}', '{$postId}')");  
  }
?>
<!-- sending response with new comment and html markup-->
<div class="comment-item">
  <div class="comment-avatar">
    <img src="<?php echo avatar($mail) ?>" alt="avatar">
  </div>
  <div class="comment-post">
    <h3><?php echo $name ?> <span>said....</span></h3>
    <p><?php echo $comment?></p>
  </div>
</div>

<?php
  // close connection
  dbConnect(0);
endif?>

Popular posts from this blog

Multiple File Upload with Progress Bar using PHP & jQuery

Some days age I have created a post that deals with How we can upload file with progress bar using php and jQuery . Some of my readers asked me how we can upload multiple files with progress bar. In this post I am going to show you how we can upload multiple files with progress bar. We can upload multiple files with progress bar exactly same way as I shown previous. But we need to do some modification with our file upload form and our php script to handle multiple files.

Multiple File Upload with PHP

Sometimes we need to allow our users to upload multiple file upload. On my previous post I was shown the basic of simple file upload with PHP. Today I am going to show you how to allow users to upload multiple files. It is almost similar like simple file upload but we need to do some modification with html markup and php code . multiple attribute is needed to add on the html markup. Major web browsers like Firefox, Chrome, Safari and IE 9+ support this attribute. Now I am going to show you how to upload multiple file with PHP and basic HTML form.

File Upload with Progress Bar using jQuery and PHP

In this post you will learn how to create a AJAX file uploading system with progress bar using jQuery and PHP. For this purpose we will going to use jQuery Form Plugin . It is a easy to use and powerful jQuery AJAX form submitting plugin. It supports XMLHttpRequest Level 2 and iframe file transportation. That's why it will work for both old and new browsers.