We organize tree comments on articles using JavaScript

    Immediately make a reservation that I am not a professional web-developer, but I am doing it just for fun, as well as for self-development.
    It was required to implement the possibility of commenting in my developments. Simple comment structures no longer interest me, so I wanted a tree view .
    At first I tried to implement it myself, but then I decided to turn to the Internet resources for drawings of the invented wheels )))

    The most interesting resources that caught my eye ( 1 , 2 , 3 , 4 ) can be read for general development.
    As a rule, most of the proposed ideas require significant changes to existing databases and the logic of the application.
    Therefore, I decided to start inventing the wheels of their original form . Unfortunately, I did not manage to provide stable and correct work on the derivation of tree-like comments using server scripts and databases only. But it turned out differently ...
    The idea came, as always suddenly. To display a full-fledged comment tree, it was required (in my case):
    • A table in MySQL with the following field names: id (int), parent (int), author (text), comment (text). The first field is the unique id of the comment, the second is parent is the id of the parent's comment, the third is author is the name of the commenter, and the fourth is comment is the comment itself.
    • Php
    • A browser with JavaScript enabled and knowledgeable about the DOM. You can read about the DOM here: http://javascript.ru/start/dom/intro

    How to get data from database tables, I can tell you no reason, I will immediately go to the php function for comment output (in the forbidden form): You can come to terms with the parameters passed by looking at the proposed table structure. Then, calling this function for each comment from the database, we pass this list (unordered!) To the browser. Now the fun part. The browser itself is able to arrange the comments in the "tree". To do this, you must call the javascript function on the user side, passing it two parameters - the comment id, and parent - the id of the “parent” comment : If the comment does not have a parent (parent = 0), then it will be the root.

    function show_comment($id,$parent,$author,$comment) {
    echo "
    $author: $comment
    ";
    }






    document.getElementById("comment"+parent).appendChild(document.getElementById("comment"+id));



    Thus, comments will be placed in the tree by the user's browser, which will reduce the load from the server and simplify the structure of the database and server scripts. But this increases the load on the browser, so you have to choose ...

    Also popular now: