Create, Rename and Delete Node using JSTree,PHP and MySQL

I got huge response from my previous article Dynamic Tree with JSTree, PHP and MySQL,Most of readers asking about how to add, edit and delete node functionality using JsTree,PHP and mysql.I will explain here how to add/edit dynamically nodes using jstree,php using AJAX.

In This Jstree PHP treemenu tutorial i am create treemenu and adding add,edit and delete node using jstree context menu.jstree context menu is a jstree plugin which is used to context menu on node, I will provide add,edit and delete node option in jstree context menu, based on selected option i ll perform add,edit and delete node using PHP as well as update MySQL tree data.

I am using JSTREE jquery plugin,You have read and understand my previous Dynamic Tree with JSTree, PHP and MySQL tutorial.

I will cover following functionality on this PHP treeview Tutorial

  • Create Simple TreeView menu using Jstree,php and mysql
  • Create context menu with add,edit and delete option
  • Add and edit node into tree menu
  • Delete single or multiple node from tree menu

You can also check other tutorial of TreeView Menu,

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

Create,Rename and Delete Node using JSTree,PHP and MySQL

The Following jsTree Plugin will use:

  • state – This plugin will use to save all opened and selected nodes state.
  • contextmenu – This plugin used show all configuration option like add,edit and delete on right click nodes.
  • wholerow – create each node appear block level which makes selection easier.

You can also check other tutorial of TreeView Menu,

Add,Edit and Delete node using jsTree and Context Menu

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: Created tree menu container in index.php.

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

Step 2: Call jstree method on div container and added context menu plugin.

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' : ['state','contextmenu','wholerow'],
        'core' : {
            'data' : {
                "url" : "response.php",
                "plugins" : [ "wholerow", "checkbox" ],
                "dataType" : "json" // needed only if you do not supply JSON headers
            }
        }
    }) 
});
</script>

above code will create context menu on right click of tree menu node.

Step 3: Now I will add context menu option and callback method for add,edit and delete jstree nodes.

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
30
31
32
33
34
35
$('#tree-container').jstree({
        'core' : {
      'data' : {
              'url' : 'response.php?operation=get_node',
              'data' : function (node) {
                return { 'id' : node.id };
              },
              "dataType" : "json"
            }
            ,'check_callback' : true,
            'themes' : {
              'responsive' : false
            }
      },
      'plugins' : ['state','contextmenu','wholerow']
    }).on('create_node.jstree', function (e, data) {
              
          $.get('response.php?operation=create_node', { 'id' : data.node.parent, 'position' : data.position, 'text' : data.node.text })
            .done(function (d) {
              data.instance.set_id(data.node, d.id);
            })
            .fail(function () {
              data.instance.refresh();
            });
        }).on('rename_node.jstree', function (e, data) {
          $.get('response.php?operation=rename_node', { 'id' : data.node.id, 'text' : data.text })
            .fail(function () {
              data.instance.refresh();
            });
        }).on('delete_node.jstree', function (e, data) {
          $.get('response.php?operation=delete_node', { 'id' : data.node.id })
            .fail(function () {
              data.instance.refresh();
            });
        });

we have create context menu and added callback option for each operation like add node,rename node and delete node,also i have added ajax request for each operation.We have create AJAX PHP request for each operation and save each modification into database using server-side response.php file.

Step 4: Now i will add server side code for update nodes information into mysql database.

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
if(isset($_GET['operation'])) {
  try {
    $result = null;
    switch($_GET['operation']) {
      case 'get_node':
        $node = isset($_GET['id']) && $_GET['id'] !== '#' ? (int)$_GET['id'] : 0;
        $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]);
        }
        $result = $data;
        break;
      case 'create_node':
        $node = isset($_GET['id']) && $_GET['id'] !== '#' ? (int)$_GET['id'] : 0;
        
        $nodeText = isset($_GET['text']) && $_GET['text'] !== '' ? $_GET['text'] : '';
        $sql ="INSERT INTO `treeview_items` (`name`, `text`, `parent_id`) VALUES('".$nodeText."', '".$nodeText."', '".$node."')";
        mysqli_query($conn, $sql);
        
        $result = array('id' => mysqli_insert_id($conn));

        break;
      case 'rename_node':
        $node = isset($_GET['id']) && $_GET['id'] !== '#' ? (int)$_GET['id'] : 0;
        //print_R($_GET);
        $nodeText = isset($_GET['text']) && $_GET['text'] !== '' ? $_GET['text'] : '';
        $sql ="UPDATE `treeview_items` SET `name`='".$nodeText."',`text`='".$nodeText."' WHERE `id`= '".$node."'";
        mysqli_query($conn, $sql);
        break;
      case 'delete_node':
        $node = isset($_GET['id']) && $_GET['id'] !== '#' ? (int)$_GET['id'] : 0;
        $sql ="DELETE FROM `treeview_items` WHERE `id`= '".$node."'";
        mysqli_query($conn, $sql);
        break;
      default:
        throw new Exception('Unsupported operation: ' . $_GET['operation']);
        break;
    }
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($result);
  }
  catch (Exception $e) {
    header($_SERVER["SERVER_PROTOCOL"] . ' 500 Server Error');
    header('Status:  500 Server Error');
    echo $e->getMessage();
  }
  die();
}

I am adding response header json type to send result in json format to jstree. I am getting 'operation' parameters which is tells which operation will perform on server side based on option click on context menu.I am processing data and storing into database and finally send json response.

Conclusion

I have added simple version of jstree with PHP,mysql and Ajax.I have added add,edit and delete node using php,mysql and jQuery AJAX.I leave copy and paste option node for you.

You can download source code and Demo from below link.

  • Elnaz

    This is a great example and works very well, thank you again Parvez 🙂

  • Freethinker Saif

    This post is awesome. Please, help me. How can I show inside a specific form when I click sub-menu with tree menu.

  • Freethinker Saif

    This post is awesome. Please help me. How can I show a specific form inside tree menu when I click sub-menu.

    • K, i ll share tutorial for this

  • Freethinker Saif

    Your every post is very much effective. I’ll be grateful to you. I tried to solve this but failed.

  • Rajessh Das

    nice example. i have added a field as link which will store the link where the sub menu will take on click . Unable to implement. I am new .Plz 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’;

  • whar are problems you are facing?

  • Nilesh kumbhar

    Error when Create
    TypeError: c is undefined……… js.min.js

  • Rahul Dubey

    i have created a database in which i hav also created a table using phpmyadmin, mysql, now i want to add treegrid in each of the column of my field values…… wat can i do isthere anyone to help me out……..

  • i thnk some jquery version error, hv u got same error on demo page as well, if not change version of jquery

  • Ashish Nanda Prasad

    Hi

    Is it possible to add a node on button click instead of pressing enter after typing

    • yes, you need to search call back