Have an account? Sign in
Login  Register  Facebook
PHP/MYSQL/jQuery Tiny comments system with multi ajax effects
[Edit] Overview
This time, we are making a Simple AJAX Commenting System. It will feature a gravatar integration and demonstrate how to achieve effective communication between jQuery and PHP/MySQL with the help of JSON.
See the demo | Download the files

[Edit] Display The Comments
PHP handles the communication with the MySQL database and generates the markup of the comments. It is also on the receiving end of the AJAX requests and inserts the comment data to the comments table
in example i have articles site and when i go to open an article i'm using article.php?id=5 url, now to display the comments for this article you have to use unique id page_id in the comments table and each comment in this article will has 5 as page_id

Comments List

We will use the php comments( $page_id ) funtion to select the comments according to its $page_id value
<?php
    // your article id
    $page_id = 5;
     
?>
<div class="comments">
    <?php
    	foreach ((array) comments($page_id) as $comment) {
    ?>
        <div class="comment shadow effect">
            <p class="left tip" title="<?php echo $comment['username'];?> Said">
                <img class="avatar" src="<?php echo get_gravatar($comment['email'],40);?>" />
            </p>
            <p class="body right">
            <?php echo nl2br($comment['comment']);?>
            <div class="details small">
                <span class="blue"><?php echo timeBetween($comment['time'],time());?></span> · <a class="red" href="#" onclick="$(this).delete_comment(<?php echo $comment['id'];?>); return false;">Remove</a>
            </div>
            </p>
            
        </div>
    <?php
    }
    ?>
</div>
To add new comment
<div class="add_comment">
    <div class="write shadow comment">
        <p class="left">
            <img class="avatar" src="#" />
        </p>
        <p class="textarea right">
            <textarea class="left" cols="40" rows="5"></textarea>
            <input class="left" value="SEND" type="submit" />
        </p>
    </div>
    <a onclick="$(this).add_comment(<?php echo $page_id;?>);return false;" class="right effect shadow" href="#">Add Comment</a>
</div>
[Edit] Javascript
We will use the jQuery and some plugins such as tipsy (to show the username on avatar hover) and the count down code

Function add_comment( page_id )

When you click add comment button This function will hide it and when you click send comment will send the comment data to the server via jquery post function
jQuery.fn.add_comment = function (page_id) {
    var that = $(this);
    // hide the "add comment" button then show the add comment box
    that.hide(10, function () {
        that.prev().show();
    });
    // in case of click the send button
    that.parent().find('input[type=submit]').click(function () {
        //your comment text
        var value = $(this).prev().val();
        //if your comment is too short
        if (value.length < 3) {
            //add red shadow on the textarea
            $(this).prev().addClass('error');
            return false;
        } else {
            var input = $(this);
            //disable textarea and the send button
            input.prev().attr('disabled', true);
            input.attr('disabled', true);
            //send the page_id,comment to the php via ajax
            $.post("ajax.php", {
                page_id: page_id,
                comment: value
            }, function (data) {
                if (data.error) {
                    alert("Your Comment Can Not Be Posted");
                } else {
                    //display the new  comment (the new comment will be tha last one) you can use .prepend() to make it the first one
                    that.parent().prev('.comments').append('<div class="comment rounded5"><p class="left"><img class="avatar" src="' + data.avatar + '" /></p><p class="body right small">' + data.comment + '<br /><div class="details small"><span class="blue">' + data.time + '</span> · <a class="red" href="#" onclick="$(this).delete_comment(' + data.id + '); return false;">Remove</a></div></p></div>');
                    //empty  the textarea
                    input.prev().val('');
                }
                //enable textarea and send button agian
                input.prev().attr('disabled', false);
                input.attr('disabled', false);
            },'json');

        }
        return false;
    });
};

Function delete_comment( id )

jQuery.fn.delete_comment = function (id) {
    var that = $(this);
    that.hide(1, function () {
        //show the count down text and cancel button
        that.parent().append('<div class="timer">It will be removed in <span class="countdown red">30</span> seconds · <a class="stop blue" href="#">Cancel</a></div>');
        //searh for the countdown class
        timer = that.parent().find('.countdown');
        //start the count down
        timer.show().countDown({
            startNumber: 30,
            startFontSize: '12px',
            endFontSize: '12px',
            //when the count down be 1
            callBack: function () {
                //send the comment id to the server
                $.post("ajax.php", {
                    remove: id
                }, function (data) {
                    //if the server return back done (the comment deleted)
                    if (data.status == 'done') {
                        //delete it from the page too
                        that.parents('.comment').remove();
                    } else {
                        $('.stop').click();
                    }
                }, 'json');
            }
        });
    });
    //when click cancel button
    $('.stop').live('click', function () {
        var parent = $(this).parent();
        //find the countdown and stop it
        parent.find('.countdown').stop();
        parent.prev().show(1, function () {
            parent.remove()
        });
        return false;
    });
};
[Edit] Save & Remove
this an example of ajax.php page
	include_once ('php/functions.php');
    // if you trying to delete
    if(isset($_POST['remove'])){
        //make it save
        $id = intval($_POST['remove']);
            //remove the comment from the database
            if(mysql_query("DELETE FROM `comments` WHERE `id` = $id")){
                exit(json_encode(array('status' => 'done')));
            }
    }
    
    if(isset($_POST['page_id']) and isset($_POST['comment'])){
        $user_id = 0;//your current user id (use 1 to comment as Billa)
        $page_id = intval($_POST['page_id']);
        $comment = mysql_escape_string($_POST['comment']);
        $time = time();
        
        if(mysql_query("INSERT INTO `comments` (`user_id`, `page_id`, `comment`, `time`) VALUES ($user_id, '{$page_id}', '{$comment}', '{$time}')")){
            $id = mysql_insert_id();
            $row = single_comment($id);
            
            exit(json_encode(array(
                'id' => $id,
                'avatar' => ($row['user_id']) ? get_gravatar($row['email'],40) : '#',
                'time' => timeBetween($row['time'],time()),
                'comment' => $row['comment'],
            )));
        }
    }
Don’t be Afraid to Ask for Help
It’s only human nature to want to hide the fact that we don’t know much about a certain topic. Nobody likes being a n00b! But how are we going to learn without asking? Feel free to use our problems section to ask more seasoned PHP developers questions.
comments ajax January 6, 2012