10.5. Adding Comments

As it stands now, what has been built functions well as a news system. Typically news posts will be short messages informing visitors as to what's new at the site or what's going on behind the scenes. Blogs, however, typically will have longer posts and invite the readers to leave their comments on the topic. I've decided to use the Ajax paradigm again to add comments.

Code must be added to view.php which will reference external JavaScript code and provides a Show Comments link:

// Javascript references
$GLOBALS['TEMPLATE']['extra_head'] = <<<ENDHTML
<script src="js/helper.js" type="text/javascript"></script>
<script src="js/blog.js" type="text/javascript">
ENDHTML;

...

while ($record = mysql_fetch_assoc($result))
{
    echo '<h2>' . $record['POST_TITLE'] . '</h2>';
    echo '<p>' . date('m/d/Y', $record['POST_DATE']) . '</p>';
    echo $record['POST_TEXT'];
    echo '<div style="display:none;" id="comments_' . $record['POST_ID'] .
        '"></div>';
    echo '<p><a href="#" onclick="toggleComments(' . $record['POST_ID'] .
        ', this);return false;">Show Comments</a></p>';
    echo '<hr/>';
}

The JavaScript code to toggle the comments display, retrieve comments for a particular post and submit new comments is then placed in public_files/js/blog.js:

// toggle the comments display of a particular post
function toggleComments(id, link)
{
    var div = document.getElementById('comments_' + id);

    if (div.style.display == 'none')
    {
        link.innerHTML = 'Hide Comments';
        fetchComments(id);
        div.style.display = '';
    }
    else
    {
        link.innerHTML = 'Show Comments';
        div.style.display = 'none';
    }
}

// retrieve existing comments via "AJAX"
window.httpObj;
function fetchComments(id)
{
    var div = document.getElementById('comments_' + id);

    var url = 'fetch.php?post_id=' + id + "&nocache=" +
        (new Date()).getTime();

    window.httpObj = createXMLHTTPObject();
    window.httpObj.open('GET', url , true);
    window.httpObj.onreadystatechange = function()
    {
        // populate the fields
        if (window.httpObj.readyState == 4 && httpObj.responseText)
        {
            div.innerHTML = httpObj.responseText;
        }
    }
    window.httpObj.send(null);
}

// submit a comment via "AJAX"
function postComment(id, form)
{
    var url = form.action + "&nocache=" + (new Date()).getTime();
    var data = 'person_name=' + escape(form.person_name.value) +
        '&post_comment=' + escape(form.post_comment.value);

    window.httpObj = createXMLHTTPObject();
    window.httpObj.open('POST', url , true);
    window.httpObj.setRequestHeader('Content-type',
        'application/x-www-form-urlencoded'),
    window.httpObj.setRequestHeader('Content-length', data.length);
    window.httpObj.setRequestHeader('Connection', 'close'),

    window.httpObj.onreadystatechange = function()
    {
        // populate the fields
        if (window.httpObj.readyState == 4 && window.httpObj.responseText)
        {
            if (window.httpObj.responseText == 'OK')
            {
                fetchComments(id);
            }
            else
            {
                alert('Error posting comment.'),
            }
        }
    }
    window.httpObj.send(data);
    return false;
}

The HTML markup displaying existing comments and the form to submit new comments is retrieved with a call from fetchComments() to public_files/fetch.php. If there are no comments, a message is included saying there are no comments for the requested post.

<?php
// include shared code
include '../lib/common.php';
include '../lib/db.php';

// retrieve comments for this post
$id = (int)$_GET['post_id'];
$query = sprintf('SELECT PERSON_NAME, POST_COMMENT, ' .
    'UNIX_TIMESTAMP(COMMENT_DATE) AS COMMENT_DATE FROM %sBLOG_COMMENT ' .
    'WHERE POST_ID = %d ORDER BY COMMENT_DATE ASC',
    DB_TBL_PREFIX, $id);
$result = mysql_query($query, $GLOBALS['DB']);

if (mysql_num_rows($result))
{
    while($row = mysql_fetch_assoc($result))
    {
        echo '<p>' . htmlspecialchars($row['POST_COMMENT']) . '<br/>';
        echo htmlspecialchars($row['PERSON_NAME']) . ' ' .
            date('m/d/Y', $row['COMMENT_DATE']) . '</p>';
    }
}
else
{
    echo '<p>There are no comments for this post.</p>';
}

// form to add comments
?>
<form action="post.php?id=<?php echo $id; ?>" method="post"
onsubmit="postComment(<?php echo $id; ?>, this); return false;">
<div>
 <label for="name_<?php echo $id; ?>">Name: </label>
 <input type="text" name="person_name" id="name_<?php echo $id; ?>"/><br />
 <label for="comment_<?php echo $id; ?>">Comment: </label>
 <textarea type="text" name="post_comment"
  id="comment_<?php echo $id; ?>"/></textarea></br>
 <input type="submit" value="submit" />
</form>

<?php
mysql_free_result($result);
mysql_close($GLOBALS['DB']);
?>

The postComment() function calls post.php to post a comment. Unlike other Ajax calls we've seen, this one is sent using the POST method because the comment can potentially contain a large amount of data and we wouldn't want to be restricted by the length limitations of GET.

public_files/post.php will return either OK if the comment is saved successfully or ERR if not.

<?php
// include shared code
include '../lib/common.php';
include '../lib/db.php';

// validate incoming values
$name = (isset($_POST['person_name'])) ? trim($_POST['person_name']) : '';
$comment = (isset($_POST['post_comment'])) ? trim($_POST['post_comment']) : '';

if ($name && $comment)
{
    // add comment
    $query = sprintf('INSERT INTO %sBLOG_COMMENT (POST_ID, PERSON_NAME, ' .
        'POST_COMMENT) VALUES (%d, "%s", "%s")',
        DB_TBL_PREFIX,
        $_GET['id'],
        htmlspecialchars($name),
        htmlspecialchars($comment));
    mysql_query($query, $GLOBALS['DB']);
    echo 'OK';
}
else
{
    echo 'ERR';
}
mysql_close($GLOBALS['DB']);
?>

Figure 10-4 shows a post with the comment area expanded

Figure 10-4. Figure 10-4

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.84.29