Dynamic Tree with JSTree, PHP and MySQL

I got huge response from my previous article How to Create Dynamic Tree View Menu,Most of readers asking about how to use checkbox with this and drag and drop features,so In this article i am creating dynamic tree menu with check box using jstree jquery tree view plugin,php and mysql. Dynamic means all nodes of tree menu is depend upon server side processing.

I am using same database structure like previous tutorial How to Create Dynamic Tree View Menu,

jstree-with-php-mysql

Why Choose JStree:

jsTree is very popular jQuery tree plugin to create awesome tree menu. jsTress is free, open source jquery treeview plugin, that help to create interactive tree menu using HTML & JSON data sources and AJAX loading. jsTree is easily extendable, them-able and configurable.It has a built in mobile theme for responsive design and various callback methods.

jsTree jQuery Tree Plugin main Features are:

  • drag & drop support
  • keyboard navigation
  • inline edit
  • create and delete
  • tri-state checkboxes
  • fuzzy searching
  • customizable node types

You can also check other tutorial of TreeView Menu,

How To create Dynamic Tree using PHP,MySQL and jquery

So we are using below files to create dynamic treeview using jstree jquery tree plugin,php and mysql. Its very easy and simple,The project structure are follows:

  1. dist folder : This folder will contains all js/css and images files.
  2. index.php : This file is use to display tree
  3. response.php : This file is use to fetch tree nodes from database and convert them into json object.

Step 1: Create Table structure to stored tree menu nodes.

Select Code
1
2
3
4
5
6
CREATE TABLE IF NOT EXISTS `treeview_items` (
`id` int(11) NOT NULL,
  `name` varchar(200) NOT NULL,
  `text` varchar(200) NOT NULL,
  `parent_id` varchar(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

Step 2: Create connection php with mysql(response.php).

Select Code
1
2
3
4
5
6
7
8
9
10
11
servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";

$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

Step 3: created PHP array of all tree nodes and encode into json(response.php).

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
$sql = "SELECT * FROM `treeview_items` ";
$res = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
    //iterate on results row and create new index array of data
    while( $row = mysqli_fetch_assoc($res) ) { 
        $data[] = $row;
    }
    $itemsByReference = array();

// Build array of item references:
foreach($data as $key => &$item) {
   $itemsByReference[$item['id']] = &$item;
   // Children array:
   $itemsByReference[$item['id']]['children'] = array();
   // Empty data class (so that json_encode adds "data: {}" ) 
   $itemsByReference[$item['id']]['data'] = new StdClass();
}

// Set items as children of the relevant parent item.
foreach($data as $key => &$item)
   if($item['parent_id'] && isset($itemsByReference[$item['parent_id']]))
      $itemsByReference [$item['parent_id']]['children'][] = &$item;

// Remove items that were added to parents elsewhere:
foreach($data as $key => &$item) {
   if($item['parent_id'] && isset($itemsByReference[$item['parent_id']]))
      unset($data[$key]);
}
// Encode:
echo json_encode($data);


Step 4:
Included all js/css files of jsTree into index.php file.

Select Code
1
2
3
4
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css">
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js"></script>
<link rel="stylesheet" href="dist/style.min.css" />
<script src="dist/jstree.min.js"></script>

Step 5: Created tree menu container in index.php.

Select Code
1
<div id="tree-container"></div>


Step 5:
Call jstree method on div container.

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<script type="text/javascript">
$(document).ready(function(){ 
    //fill data to tree  with AJAX call
    $('#tree-container').jstree({
    'plugins': ["wholerow", "checkbox"],
        'core' : {
            'data' : {
                "url" : "response.php",
                "plugins" : [ "wholerow", "checkbox" ],
                "dataType" : "json" // needed only if you do not supply JSON headers
            }
        }
    }) 
});
</script>

You can see here, we are using "checkbox" plugin to create check-box against each node.We are passing json data to jstree method.
You can download source code and Demo from below link.

  • Rajessh Das

    hi sir, I have used the code and its working fine. I have added a field as link which will hold the target for child nodes . On clicking the same it will redirect the same to that page. How to implement the same. Can anyone help.

    • Hi Rajessh,
      I got some time to solve ur problem, You need to add below changes to add href in you all node anchor tag but on-click to ridrect you need to debugging on jstree call back function.
      You can add href attribute and value using below code,
      //already have in you code
      $itemsByReference[$item[‘id’]][‘data’] = new StdClass();

      add below two lines

      $itemsByReference[$item[‘id’]][‘a_attr’] = new StdClass();
      $itemsByReference[$item[‘id’]][‘a_attr’]->href = ‘google.com’;

  • Nilesh kumbhar

    Hi how can i add grid.

    Eg.

    Node price
    item1 342

    item2 333

    like this

    • you can change node text value using mysql text field.

  • Peter Maly

    I copied all the snippets into right php files but have no output… 🙁 the code is not working… it is not something outdated due new version of jsTree ???

    The hard-coded data works well, also the code from article “How to Create Dynamic Tree View Menu” – that I adapted on My custom database successfully, but this JSON is My nightmare… 🙁

    • i am using 3.2.1 stable version,have u compared JSON object of hardcoded and php generated,

  • i used SELECT * FROM `treeview_items query,so i do not use column name

    • Muhammad Ferry

      But if i change column name “text”, the data is not show.
      How to fix this?

      • soryy actually jstree must have ‘text’ field json for node label name, so u need to change column name after select * query, so u will rebuild fetched mysql array data.

  • Giuseppe

    FIrst thanks for the tutorial. I don’t understand why you pass item as reference (not expert on PHP tricks), but well, I will study this. About the tutorial, I can’t get it working. I tried my own, and got an empty tree. Then I saw there is a sample download, but I get the same result. Some idea why? https://uploads.disquscdn.com/images/65a9bf823b87d807bac4a9bfd6b78cc56c3c4563380e893cfdee78dc0eab2ce0.png

    • Peter

      Hi Giuseppe,

      It took me some hours to find out since I’m not well versed in PHP and JSON, but it seems that the file outputs the keys in the JSON which messes up the structure (in your screenshot the first characters {“1”: for example). You can avoid this by changing the last line to:

      echo json_encode(array_values($data));

      For more information on array_values check: http://php.net/manual/en/function.array-values.php

  • Bushra Rehan

    How to add a file name under the tree which with a hyper link??

  • $sql = “SELECT id, title AS text, parent_id FROM my_table ;”

    If for example in the DB the name of the column is “title”, in the returned array it’s aliased to “text”.