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 ...

Get PHP and MySQL®: Create-Modify-Reuse now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.