Simple jQuery Ajax Comment System in Php

Simple jQuery Ajax Comment System in Php
Simple jQuery Ajax Comment System in Php
It looks very annoying when we submit comment and wait till the whole page gets load to check our comments added successfully. But what if don’t want to refresh/reload the page after submitting our comments? Here the solution is jQuery Ajax comment box. 
In this tutorial of PHP Tutorials for Beginners I will show you how to create Comment box without refreshing page with jQuery Ajax and Php. We will use jQuery Ajax for comment system so that the page will not refresh while adding or updating comment.

Please follow step by step to create jQuery Ajax Comment box with Php. 

Step 1:- First step is to create a table in you database. We have create as "comments" table in our example.

CREATE TABLE IF NOT EXISTS `comments` (
  `id` int(5) NOT NULL AUTO_INCREMENT,
  `post_id` int(5) NOT NULL,
  `name` varchar(20) NOT NULL,
  `email` varchar(10) NOT NULL,
  `comment` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ;
Step 2:- Next step is to create our config.php file which will contain your database connection code.
<?php $database = “practice”; // the name of the database. $server = “localhost”; // server to connect to. $db_user = “root”; // mysql username to access the database with. $db_pass = “”; // mysql password to access the database with. $table = “comments”; // the table that this script will set up and use. $link = mysql_connect($server, $db_user, $db_pass); mysql_select_db($database, $link); ?>
Step 3:- Now the next step is to create an index.php page which contain your Front end Comment box code.
<script type=”text/javascript” src=”jquery.js”></script>
<script type=”text/javascript” src=”common.js”></script>
<link rel=”stylesheet” type=”text/css” href=”style.css” />
<?php
/* Including database connection file. */
include(‘config.php’);
session_start();
/*
  The below SESSION is very important step.
  Here we have stored post id into session,
  which is used while inserting and fetchig data from database.
  I have used static id ie “1″. So please replace this with your POST ID.
 */
$_SESSION['postid'] = 1;
?>

<!–
The below “Write Your Comment” link will use to show Ajax Comment Box on clicking on it.
–>
<h3 class=”comment form-signin”><a href=”#” onclick = “show_comment_box();”>Write Your Comments</a></h3>

<!–
The below div will show the Ajax Comment Box.
Initially I have made Ajax Comment Box hidden.
If you want to show it on page load it self then remove the style=”display: none;” line from it.
–>
<div class=”comment_box container login form-signin” style=”display: none;”>
     <div>
        <div>
            <input type=”text” class = “name” value=”Enter your name” name=”” onblur=”if(this.value == ”){this.value =’Enter your name’}” onfocus=”if(this.value == ‘Enter your name’) {this.value=”}” />
        </div>
        <div>
            <input type=”text” class = “email” value=”Enter your email” name=”” onblur=”if(this.value == ”){this.value =’Enter your email’}” onfocus=”if(this.value == ‘Enter your email’) {this.value=”}” />
        </div>
        <textarea onblur=”if(this.value == ”){this.value =’Enter your comment’}” onfocus=”if(this.value == ‘Enter your comment’) {this.value=”}”  class = “user_comment”  rows=”5″ cols=”60″ name=””>Enter your comment</textarea>
    </div>
    <span><a onclick=”submit_review()” href=”javascript:void(0)” class=”btn btn-large btn-primary”>Submit</a></span> |
    <span><a onclick=”cancel()” href=”javascript:void(0)” class=”btn btn-large btn-primary”>Cancel</a></span>
    <input type=”hidden” id=”post_id” value=”<?php echo $_SESSION['postid']; ?>” />
</div>

<!–
The below div will show the successful message after comment is added into database.
–>
<div class=”message”></div>

<!–
The below div will show the list of all comments for that perticular post.
–>
<div class=”comment_list form-signin”>
     <h3>User’s Comment on this Article:-</h3>
         <?php
         $query = “SELECT * FROM comments where post_id = ”.$_SESSION['postid'];
         $result = mysql_query($query);
         while ($res = mysql_fetch_array($result)) {
             ?>
        <label style=”font-size:18″>Name:-<?php echo $res['name']; ?></label>
        <label>Comment:-<?php echo $res['comment']; ?></label><br>
<?php } ?>
</div>
Step 4:- Now the next step is to make "common.js" page which we have included in index.php. This file contain all the functions and ajax request which are called while commenting.
function show_comment_box(){
        $(“.comment_box”).show();
    }

    function submit_review(){
        /*
        In below code we have first stored the values of post id,name,email and comment in some varialbles.
         */
        var id = $(‘#post_id’).val();
        var name = $(‘.name’).val();
        var email = $(‘.email’).val();
        var comment = $(‘.user_comment’).val();
        /*
        In below code we checking if user have entered all feilds or not?
         */
        if(comment != “Enter your comment” && name != “Enter your name” && email != “Enter your email”){
            $(‘body’).css(‘cursor’, ‘progress’);
          /*
            In below code we are passing the data to external url which contain the code to add our inputs into database.
           */
            $.ajax({
                type: “POST”,
                url: “http://localhost/ajax_comment_box/add_comment.php”,
                data: { pid:id,user_name:name, user_email:email, user_comment:comment}
            }).done(function( result ) {
                setTimeout( function(){
                    if(result == “”){
                        $(“.message”).html(“Your comment is added successfully.”);
                        $(‘.comment_list’).fadeOut([30]).load(‘http://localhost/ajax_comment_box/reload_comment.php’).fadeIn([10]);
                        $(“.name”).val(‘Enter your name’);
                        $(“.email”).val(‘Enter your email’);
                        $(“.user_comment”).val(‘Enter your comment’);
                        $(“.comment_box”).hide();
                        $(‘body’).css(‘cursor’, ‘auto’);
                    }
                }, 2000);
            });
        }else{
            alert(“Please fill all the field!!!”);
        }
    }

    function cancel(){
        $(“.comment_box”).hide();
        $(“.name”).val(‘Enter your name’);
        $(“.email”).val(‘Enter your email’);
        $(“.user_comment”).val(‘Enter your comment’);
    }
Step 5:- This is the second last step while creating jQuery Ajax Comment Box. In this step we will create file called "add_comment.php". This file will be called when ajax request is made after submitting comment and it will insert the data into database.
<?php
    include(‘config.php’);
    $post_id = $_POST['pid'];
    $name = $_POST['user_name'];
    $email = $_POST['user_email'];
    $comment = $_POST['user_comment'];
    $query = “INSERT INTO comments(post_id, name, email, comment) VALUES(‘$post_id ’,’$name ’,’$email ’,’$comment’)”;
    mysql_query($query) or die (“MySQL Error.”);
?>
Step 6:- This is the last step of jQuery Ajax Comment Box. In this step we will create file called "reload_comment.php". After successful data insertion we need to update the comment list, so "reload_comment.php" will be called at that time and it will update the comments without refreshing the page.
<?php
    session_start();
    include(“config.php”);
    $query = “SELECT * FROM comments where post_id=”.$_SESSION['postid'];
    $result = mysql_query($query);
    while($res=mysql_fetch_array($result)){ ?>
    <div style=”font-size:18″>Name:-<?php echo $res['name']; ?></div>
    <div>Comment:-<?php echo $res['comment']; ?></div><br>
<?php } ?>
Hope this php tutorial is useful for you. Keep following Php Point for more examples.

1 comment:

  1. Watch Online Movies without Registration and without ads. Watch 123movies, putlocker, fmovies, yesmovies, movies123

    123Movies

    ReplyDelete