Create Treeview with jsTree plugin and PHP

If you already managing the relationship between parent and child items using a separate field then it is easier to create a hierarchical structure.

With the use of a jsTree plugin, this will be created in less time.

jsTree is a jQuery plugin that creates a hierarchical data structure using JSON data.

It allows setting icon of a node, by default open, disable a node and set it selected while initializing, etc.

In this tutorial, I show how you can make a tree structure of MySQL data using jsTree plugin and PHP.

Create treeview with jsTree plugin and PHP


Table of Content

  1. Create a Table and Insert Data
  2. Create Database Connection file
  3. Download & Include jstree plugin
  4. HTML & PHP – Create Layout for jsTree
  5. jQuery – Initialize jsTree
  6. Demo
  7. Conclusion

1. Create a Table and Insert Data

I am using folders table in the example –

CREATE TABLE `folders` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(80) NOT NULL,
  `parentid` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

It has the following data –

INSERT INTO `folders` (`id`, `name`, `parentid`) VALUES
(1, 'Folder1', 0),
(2, 'Folder2', 0),
(3, 'Folder 1 sub1', 1),
(4, 'Folder 1 sub1.1', 3),
(5, 'Folder 1 sub1.2', 3),
(6, 'Folder 1 sub1.1.1', 4),
(7, 'Folder 1 sub2', 1),
(8, 'Folder 1 sub3', 1),
(9, 'Folder 1 sub3.1', 8),
(10, 'Folder 2 sub1', 2),
(11, 'Folder 2 sub1.1', 10),
(12, 'Folder 2 sub1.2', 10),
(13, 'Folder 2 sub2', 2),
(14, 'Folder 3', 0);

I stored parent id value in parentid field.


2. Create Database Connection file

Create config.php for the database connection.

<?php

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}

3. Download & Include jsTree plugin

  • Download the jsTree plugin from the official website.
  • Include jsTree style.min.css, jQuery library, and jstree.min.js file.
<link rel="stylesheet" type="text/css" href="jstree/dist/themes/default/style.min.css">

<script src="jquery-3.4.1.min.js"></script>

<script type="text/javascript" src="jstree/dist/jstree.min.js"></script>

Or you can use CDN –

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>

4. HTML & PHP – Create Layout for jsTree

Fetch all records from folders table and loop on it.

Here’s what the data should look like in a JSON format for jsTree setup:

{
   "id": [id], 
   "parent": [parentid], 
   "text": [text],
   "state": {
      "selected": [boolean-value],
      "opened": [boolean-value]
   }
}

NOTE – If parent id is 0 then pass ‘#’.

  • With PHP create an Array and encode it into JSON format.
  • If the $parent_id equals 0, set $parent_id to ‘#’.
  • If you want to select and open a node with an ID of 2, set the $selected and $opened variables to true.
  • Start by initializing an$folders_arr Array with keys: id, parent, text, and state.
  • Create <div id='folder_jstree'> to initialize jsTree and <textarea id='txt_folderjsondata' > to store $folders_arr Array in JSON format.

Completed Code

<?php 
include "config.php";
?>

<!DOCTYPE html>
<html>
<head>
    <title>Create Treeview with jsTree plugin and PHP</title>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
</head>
<body>
    <?php 
    $folderData = mysqli_query($con,"SELECT * FROM folders");

    $folders_arr = array();
    while($row = mysqli_fetch_assoc($folderData)){
         $parentid = $row['parentid'];
         if($parentid == '0') $parentid = "#";

         $selected = false;$opened = false;
         if($row['id'] == 2){
              $selected = true;$opened = true;
         }
         $folders_arr[] = array(
              "id" => $row['id'],
              "parent" => $parentid,
              "text" => $row['name'],
              "state" => array("selected" => $selected,"opened"=>$opened) 
         );
    }

    ?>

    <!-- Initialize jsTree -->
    <div id="folder_jstree"></div>

    <!-- Store folder list in JSON format -->
    <textarea id='txt_folderjsondata'><?= json_encode($folders_arr) ?></textarea>

</body>
</html>

5. jQuery – Initialize jsTree

Read Data:

Retrieve the data from the #txt_folderjsondata element. This data will be in JSON format.

Convert to JSON Object:

Convert the data into a JSON object and store it in folder_jsondata variable .

Initialize jsTree:

Set up the jsTree plugin on the #folder_jstree element.

Core Data Option:

Configure the jsTree’s core data option. Use the folder_jsondata as the data source.

Disable Multiple Selection:

Make sure that users can’t select multiple nodes simultaneously by setting the multiple option to false.

Completed Code

$(document).ready(function(){
   var folder_jsondata = JSON.parse($('#txt_folderjsondata').val());

   $('#folder_jstree').jstree({ 'core' : {
      'data' : folder_jsondata,
      'multiple': false
   } });

});

6. Demo

View Demo


7. Conclusion

If parentid is equaled to 0 then assign ‘#’ to parent key.

Remember, it’s essential to provide the JSON data in the correct format; otherwise, the initialization won’t work.

If you found this tutorial helpful then don't forget to share.

7 thoughts on “Create Treeview with jsTree plugin and PHP”

  1. Hello my friend and thanks for this tutorial, I have question and a problem unfortunately….
    I’ve tried to decode in jSon an associative array I’ve created from a web service and for some reason the resulted jSon is not formed well as the one in this tutorial and demo.
    Why ?
    this is my PHP array produced from an HTML string:
    $new_string = explode(‘|’,$html_val->nodeValue);

    //$str = “9|Engineering”; // $re = explode(‘|’, $str); // echo $re[1];//Engineering

    $padre = $new_string[0]; //echo ‘padre: ‘.$padre.”;
    $figlio = $new_string[1]; //echo ‘figlio: ‘.$figlio.”;
    $desc = $new_string[2]; //echo ‘desc: ‘.$desc.”;
    $colore = $new_string[3]; //echo ‘colore: ‘.$colore.”;
    $lt = $new_string[4]; //echo ‘lt: ‘.$lt.”;
    $pallino = $new_string[5];
    $magazz = $new_string[6]; //echo ‘magazzino: ‘.$magazz;

    $trenino[‘parent’][] = $new_string[0];
    $trenino[‘id’][] = $new_string[1];
    $trenino[‘name’][] = $new_string[2];
    $trenino[‘colore’][] = $new_string[3];
    $trenino[‘lt’][] = $new_string[4];
    $trenino[‘pallino’][] = $new_string[5];
    $trenino[‘magazz’][] = $new_string[6]

    and this is part of my jSon produced from json_encode($trenino) :
    {“parent”:[“”],”id”:[“MY00027770096″],”name”:[“REJANE 85MM BOTTONE E CHIAVE “],”colore”:[“50FF15″],”lt”:[“0″],”pallino”:[“”],”magazz”:[“NP”]}

    Reply
  2. Wow, this jQuery tree works very well.
    I was wondering if it’s possible for me to detect the specific node I’ve (control) clicked on and obtain the associated $row[‘id’]…and perhaps save that in a php session variable. I’d like ot save the selected tree node value so that I can use that value in my code somwehere else. I can’t figure out how to do this.

    Thanks!
    Binit

    Reply

Leave a Comment