Creating AJAX comment system

There are few parts to this system:

  1. Display Comments
  2. Enter Comments
  3. AJAX Submit to PHP file
  4. Create Database to store Comments
  5. PHP file update database and return to AJAX
  6. Connect to Database to retrieve all comments

PART 1.  HTML DISPLAY TEMPLATE.

    <div class="cmt-cnt">
        <div class="thecom">
            <img width="50px" height="50px" src="http://placehold.it/350x150" class="img-circle">
            <h5><?php echo $comment['Name'] ?></h5><span data-utime="1371248446" class="com-dt"><?php echo $comment['timeStamp'] ?></span>
            <br/>
            <p>
                <?php echo $comment['comment'] ?></p>
        </div>
    </div>
    <br>

in order for the data to be populated from database later, php echo variable is placed at the html value. For the CSS to control the look and feel as follows:

<style>

.cmt-cnt{
    width: 100%; height: auto; min-height: 35px; 
    padding: 5px 0;
    overflow: auto;
}
.cmt-cnt img{
    float: left; 
    margin-right: 10px;
}
    .thecom{
    width: auto; height: auto; min-height: 35px; 
    background-color: #fff;
    }
    .thecom h5{
        display: inline;
        float: left;
        font-family: tahoma;
        font-size: 13px;
        color: #3b5998;
        margin: 0 15px 0 0;
    }
    .thecom .com-dt{
        display: inline;
        float: left;
        font-size: 12px; 
        line-height: 18px;
        color: #ccc;
    }
</style>

PART 2. ENTER COMMENTS USING JQUERY

<?php if($memberId != null) { ?>
    <div id="new-com-bt">
        <span>Write a comment ...</span>
    </div>
    <div id="new-com-cnt">    
        <textarea class="form-control" id="post"></textarea>
        <input type="hidden" id="memberId" value="<?php echo $memberId ?>">
        <input type="hidden" id="projId" value="<?php echo $project[0][Project_id] ?>">
        <div  class="pull-right">
        <button type="submit" id="postbtn" class="btn btn-default">Post comment</button>
        <button type="cancel" id="cancelbtn" class="btn btn-default">Cancel</button>
       </div>
    </div>

    <div class="clear"></div>
</div><!-- end of comments container "cmt-container" -->
<?php } ?>

First the HTML template to create a new message, here We first use php to test if the user is logged in before allowing to post Comments

PART 3. AJAX Submit to PHP file

The following Javascript using Ajax to control the UX as well as submit the comment field to comment.php for processing

<script>
$( document ).ready(function() {
        $('#new-com-cnt').hide();
        $("#postbtn").css({opacity:0.6});
        $('#new-com-bt').click(function(event){    
                $(this).hide();
                $('#new-com-cnt').show();
            });

        /* when start writing the comment activate the "add" button */
        $('#post').bind('input propertychange', function() {
           $("#postbtn").css({opacity:0.6});
           var checklength = $(this).val().length;
           if(checklength){ $("#postbtn").css({opacity:1}); }
        });

        /* on clic  on the cancel button */
                $('#cancelbtn').click(function(){
                    $('#post').val('');
                    $('#new-com-cnt').fadeOut('fast', function(){
                        $('#new-com-bt').fadeIn('fast');
                    });
                });
        // on post comment click 
        $('#postbtn').click(function(){
            var theCom = $('#post');
            var theMember = $('#memberId');
            var theProf = $('#projId');

            if( !theCom.val()){ 
                alert('You need to write a comment!'); 
            }else{ 
                //alert('act=add-com&member='+theMember.val()+'&project='+theProf.val()+'&comment='+theCom.val()); 
                $.ajax({
                    type: "POST",
                    url: "comment.php",
                    data: 'act=add-com&member='+theMember.val()+'&project='+theProf.val()+'&comment='+theCom.val(),
                    success: function(html){
                        theCom.val('');
                        theMember.val('');
                        theProf.val('');
                        $('#new-com-cnt').hide('fast', function(){
                            $('#new-com-bt').show('fast');
                            $('#new-com-bt').before(html);  
                        })
                    }  
                });
            }
        });

});
</script>

PART 4 Create Database to store Comments

Simply create the database table member through following:

CREATE TABLE member (
  Member_id int(11) NOT NULL AUTO_INCREMENT,
  Name varchar(45) CHARACTER SET latin1 DEFAULT NULL,
  Surname varchar(45) CHARACTER SET latin1 DEFAULT NULL,
  Email varchar(45) CHARACTER SET latin1 DEFAULT NULL,
  Password char(255) CHARACTER SET latin1 DEFAULT NULL,
  Salt char(255) CHARACTER SET latin1 DEFAULT NULL,
  Member_type int(11) DEFAULT NULL,
  Address varchar(45) CHARACTER SET latin1 DEFAULT NULL,
  Postal_code varchar(45) CHARACTER SET latin1 DEFAULT NULL,
  Country varchar(45) CHARACTER SET latin1 DEFAULT NULL,
  Ip_address varchar(45) CHARACTER SET latin1 DEFAULT NULL,
  Contact_number varchar(45) CHARACTER SET latin1 DEFAULT NULL,
  Activated int(11) DEFAULT NULL,
  Activated_date timestamp NULL DEFAULT NULL,
  Gender varchar(45) CHARACTER SET latin1 DEFAULT NULL,
  Date_of_birth datetime DEFAULT NULL,
  Activate_code varchar(45) CHARACTER SET latin1 DEFAULT NULL,
  Reset_password_code varchar(45) DEFAULT NULL,
  Mobile_number varchar(45) DEFAULT NULL,
  Writeup varchar(45) DEFAULT NULL,
  PRIMARY KEY (Member_id)
) ENGINE=MyISAM AUTO_INCREMENT=1095 DEFAULT CHARSET=utf8;

PART 5 UPDATE DATABASE AND UPDATE AJAX THROUGH PHP

 

<?php
//------------------------ getting the commenting from AJAX -------------------------
extract($_POST);

if($_POST['act'] == 'add-com'):

    $name = htmlentities($name);
    $email = htmlentities($email);
    $comment = htmlentities($comment);

            $member = htmlentities($member);
            $project = htmlentities($project);
            $comment = htmlentities($comment);
            //$comment = htmlentities($comment);

            //echo '<pre>', print_r($_POST['act'], true), '</pre>';

            $member_esc = $db->mysql_escape($member);
            $project_esc = $db->mysql_escape($project);
            $comment_esc = $db->mysql_escape($comment);

            $query ="INSERT INTO comments (memberID, projectID, comment) VALUE ('$member_esc', '$project_esc', '$comment_esc')";
            $result = $db->writeQuery($query);

            $query2 = "SELECT * FROM member WHERE Member_id ='$member_esc'";
            $members = $db->readQuery($query2);

            if($result =! null){
                ?>
                    <div class="cmt-cnt">
                        <img width="50px" height="50px" src="http://placehold.it/350x150" class="img-circle">
                        <div class="thecom">
                            <h5><?php echo $members['0']['Name']; ?></h5><span  class="com-dt"><?php echo date('d-m-Y H:i'); ?></span>
                            <br/>
                            <p><?php echo $comment; ?></p>
                        </div>
                    </div><br><!-- end "cmt-cnt" -->
        <?php } ?>
<?php endif; 
//----------------------------- end of getting AJAX ---------------------------
?>

PART 6, COLLECT DATABASE COMMENTS AND POPULATE THE COMMENTS IN HTML

if(($memberId != null) && ($project[0][Project_id] != null)){

    $projectID = $project[0][Project_id];

    $query = "SELECT * FROM comments 
    INNER JOIN member
    ON comments.memberID = member.Member_id
     WHERE (memberId='$memberId' && projectID='$projectID') 
     ORDER BY comments.timeStamp ASC";
    $comments = $db->readQuery($query);
}