Php

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,

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.

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

View Comments

  • 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';

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

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

    • 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

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

  • 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

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

  • 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

    • there is callback method on chkbox onchane, u need to get more details from official docs.

Recent Posts

Configure and Retrieve S3 Information Using Laravel PHP-AWS-SDK

This tutorial helps integrate a PHP SDK with Laravel. We'll install aws-php-sdk into laravel application and access all aws services… Read More

2 months ago

What is the Purpose of php_eol in PHP?

in this quick PHP tutorial, We'll discuss php_eol with examples. PHP_EOL is a predefined constant in PHP and represents an… Read More

8 months ago

Laravel Table Relationship Methods With Example

This Laravel tutorial helps to understand table Relationships using Elequonte ORM. We'll explore laravel table Relationships usage and best practices… Read More

8 months ago

Exploring the Power of Laravel Eloquent Join?

We'll explore different join methods of Laravel eloquent with examples. The join helps to fetch the data from multiple database… Read More

9 months ago

Quick and Easy Installation of Laravel Valet

in this Laravel tutorial, We'll explore valet, which is a development environment for macOS minimalists. It's a lightweight Laravel development… Read More

9 months ago

What is Laravel Soft Delete and How Does it Work?

I'll go through how to use soft delete in Laravel 10 in this post. The soft deletes are a method… Read More

9 months ago

Categories