Categories: Php

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

I got a huge response from my previous article Dynamic Tree with JSTree, PHP and MySQL, Most of the readers asked 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 creating a multi-level tree menu and adding add, edit and delete nodes using jstree context menu.

jstree context menu is a jstree plugin that is used to show the context menu on the node, I will provide add, edit and delete node option using jstree context menu on each node, based on the selected option I’ll perform add, edit and delete a node using PHP as well as update MySQL tree data.

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

I will cover the following functionality in 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 the same database structure as previous tutorial How to Create Dynamic Tree View Menu,

The Following jsTree Plugin will use:

  • state – This jstree plugin will use to save all opened and selected nodes state.
  • contextmenu – This jstree plugin is used to show all configuration options like add, edit and delete on right-click nodes.
  • wholerow – This plugin help to 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

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 follows:

  1. dist folder: This folder will contain all js/css and images files.
  2. index.php: This file is used to display tree
  3. response.php: This file is used to fetch tree nodes from the database and convert them into JSON objects.

Step 1: Created a tree menu container in index.php file.

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

Step 2: Now, I’ll call jstree method on the div container and added the context menu plugin.

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

The above code will create a context menu on the right click of the Treeview node.

Step 3: Let’s add a context menu option and callback method for add, edit and delete jstree nodes.

$('#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 created a context menu and added a callback option for each operation like add a node, rename node and delete a node. Also, I have added ajax requests for each operation. We have created AJAX PHP request for each operation and saved each modification into the database using server-side response.php file.

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

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 content-type is JSON, That help to send a response in JSON format to the jstree.

I am getting 'operation' parameters that notify which operation will perform on the server side based on the selected option on the context menu.

I am processing data and storing it into the database and finally sending JSON response to the UI.

Conclusion

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

You can download source code and Demo from the below link.

Tags: jstree

View Comments

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