• View our reviews on Hot Scripts
  • JS Tutorial

Recent Comments

Powered by Disqus

Back to articles

Javascript tree view

There is one cool javascript tree view script, that is called dtree. You can find it here: It allows you to create tree view categories like this: 

We will implement this into form, so we can submit ID of chosen category, and we will also update tree using jQuery AJAX request.

So first thing we need to do is to get all categories out of database and put it into json structure. We can use Recursive function from here and modify it to fit our needs, and we get this:

//category title
echo "[{ rowid:'0', prnt:'-1', catname:'Category tree', ahref:''}";
function print_tree($id = 0) 
    //getting parent categories (you can use your own mysql class 
    //or simple mysql connection)
    $result = $query->select_result("*", "category", "where prnt='0'");
    //checking if there are any results
    if($result != 0)
        //outputing categories and checking children of every category
        while($row = $query->fetch($result))
            echo ",{ rowid:'".$row['ID']."', prnt:'".$id."', ".
                    "catname:'".$row['category_name']."', ".
//calling function
echo "]";
  • rowid represent unique identifies of row
  • prnt - identifier of parent category
  • catname - name of the category
  • ahref - link where to go, when clicked on category (in our case we will use javascript function to insert ID into hidden form field)

Here is the function that will get the ID of selected category:

//putting ID of selected category into form hidden field
function category(id)
    document.getElementById("category").value = id;

And this is how we will create tree using jQuery AJAX based on json structure:

//drawing or redrawing tree
function draw_tree()
    $.getJSON("tree.php",{atr: 1, ajax: 'true'}, function(j){
        //creating dtree instance
        d = new dTree('d');
        for (var i = 0; i < j.length; i++) 
            //creating nodes based on generated json data
            d.add(j[i].rowid, j[i].prnt, j[i].catname, j[i].ahref);
        document.getElementById('tree').innerHTML = d;


And this is our simple form:

<div id='tree'>
<script type='text/javascript'>
<form method='post' action=''>
<input type='hidden' name='cat_ID' id='category'/>
<p><input type='submit' value='Add'/></p>

So why did we need to update tree dynamically using AJAX? You can add functionality to add new categories to tree and automatically update tree, so if you fill form and then realize you don't have needed category, then you can update it without loosing inputted form data.

You may also be interested in:

Powered by

blog comments powered by Disqus