Dynamic Tree with JSTree, PHP and MySQL

I got huge response from my previous article How to Create Dynamic Tree View Menu, Most of the readers asked about how to use the checkbox with this and drag and drop features.

In this article, I am creating a dynamic tree menu with checkbox using jstree jquery tree view plugin, PHP and MySQL. Dynamic means all nodes of the tree menu depend upon the server side processing.

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

jstree-with-php-mysql

Why Choose JStree:

jsTree is a very popular jQuery tree plugin to create an awesome multi-level menus. The jsTress is free, open-source jquery treeview plugin, that helps to create an 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,

Video Tutorial:

If you are more comfortable in watching a video that explains Dynamic Tree with JSTree, PHP and MySQL, then you should watch this video tutorial.

Create a Dynamic Tree using PHP, MySQL and jquery

So we are using the below files to create a 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 contain all js/css and images files.
  2. index.php: This file is used to display tree menu.
  3. response.php: This file is used to fetch tree nodes from the database and convert them into json object.

Step 1: Create a Table structure to store tree menu nodes. We need to create a ‘test’ database(if you have then don’t need it) and created it below 'treeview_items' table into this database.

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: Created connection with MySQL into (response.php) file.

$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 it into json(response.php) file.

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

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

<div id="tree-container"></div>

</pre>

Step 6: Call jstree method on div container.

<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 a check-box against each node. We are passing JSON data to jstree method.

You can download source code and Demo from below link.

31 thoughts on “Dynamic Tree with JSTree, PHP and MySQL

  1. 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’;

        • you can add this code with jstree to redirect on href page.

          jstree().bind(“select_node.jstree”, function (e, data) {

          var href = data.node.a_attr.href;

          document.location.href = href;

          //console.log(href);

          })

        • you can get full refrence from https://phpflow.com/php/advanced-treeview-menu-using-jstree-with-php-and-mysql/ tutorial.

  2. 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… 🙁

  3. Hello

    How change database column name?
    The colum must be “text”?
    I did’t found “text” call funtion on response.php

    Thanks

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

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

    • 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

  5. $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”.

  6. Hello,

    Thanks for this tutorial. I have use this example with a
    menu to set the authorisation. The response.php is working well in
    combination with the database, the whole tree is build correctly. But
    how can I, when the page just is build, set the checkboxes when the
    pages is opening?

    Can I do this in Response.php? But how? Or need
    this the be done in jQuery after the full tree is build and set then the
    checkboxes by there id?

    Or did write it down already somewere, because it seems to me that I’m not the first one with question.

    Thanks,

    Nico

    • you can take reference from this jstree tutorial , https://phpflow.com/php/create-rename-delete-node-using-jstree-php-mysql/

      • Thank you very much ! This is exactly what i wanted. I was able to easily enter this modification into the code.
        And lastly, to finish my app, i would like to be able to complete the script using the following 3 buttons « edit » « delete » and « view » wrote in the example, but by displaying a pop-up instead of a new web-page then add a general button that says « add ».
        If you have a moment, kindly.

        • you need to remove context menu and add redirect logic to add page view on click of node href attribute.

  7. Hello,

    Thanks for this tutorial. I have use this example with a
    menu to set the authorisation. The response.php is working well in
    combination with the database, the whole tree is build correctly. But i want to get value of each checkbox on selection ,please help me

Leave a Reply

Your email address will not be published.