Adding comments to static web pages

Want to know what reader are thinking of your article? You can install a complete content management system, and spend some week to move your pages and try to let the system look as you previous website, or to use a standalone, easy to install specialized tool.

The comment system is very simple:
- each page that has to be commented, has a companion XML file that holds all the comments for this page.
- when the article is displayed, the content of the XML file is loaded dynamically by an Ajax script and the comment displayed at bottom of the page.
- an authentification script is used also with an XML file to store the logins, passwords, e-mail addresses, etc...

For the first demonstration, a single comment may be entered by the reader and it is saved into the demo-comment.xml file, then the current page is reloaded, the XML file is loaded by an Ajax script, and the content is parsed and displayed at bottom of this page.

Here is the code that scans the XML file using the getElementByTagName() and getElementById() DOM's methods.

function processData(doc)
  var element = doc.getElementsByTagName('login').item(0);
doc.getElementsByTagName('comment').item(0); }

Adding a comment to a page, demonstration

In the real application, a login and password are checked first, the comment will be added to an XML file with other comments and the content of this file is dynamically added to the web page at loading. Boxes will be created for each comment.
A complete manager allowing to view and delete comments will be further available to complete the tool.
The template of your pages have to include the JavaScript code.

  1. In the form, add a comment and your login (type anything).
    Click on the "Add comment" button.
  2. The page is reloaded and the login and the comment are displayed in the box at bottom.

Multiple comments and users

The next step is the support of many comments by different users. The XML file to store the comments has the following format:

  <comment login="" post=""/>

The generation of the file uses DOMDocument's methods in PHP 5 :


$doc = new DOMDocument("1.0", "UTF-8");
$comtag= $doc->createElement("comment");
$comtag->setAttribute("login", $login);
$comtag->setAttribute("post", $comment);


The JavaScript file retrieves the content to load the page with an Ajax function and transfers the XML data into an array.

function checkComments(xcontent)
  var dnl = xcontent.getElementsByTagName("comment");
  var arr = new Array();
  for(i=0;i< dnl.length;i++)
    var e = dnl.item(i);
    var login = unescape(e.getAttribute("login"));
    var comment = unescape(e.getAttribute("post"));
    arr[i] = new Array(login, comment);
  return arr;

The full source code is in the archive.