Php

Advanced JSTree with PHP and MYSQL

In This jstree tutorial, I will let you know how to add search and render content on click of node in JSTree using PHP and jQuery. I got huge responses from my previous article Dynamic Tree with JSTree, PHP and MySQL.

I have shared one more tutorial for dynamic add, edit and delete node using JSTree and php. You can learn from Create, Rename and Delete Node using JSTree,PHP and MySQL.

Most of the user request to share an article about render or redirect on the page when the user clicks the leaf node in jstree.I have also added search functionality in jstree using the search plugin.

There are a lot of jquery plugins available in the market which are generating tree structures using json objects. I shared an article 10+ Most Popular jQuery Tree Menu Plugin.

jstree is free, open-source jquery treeview plugin, that helps to create an interactive tree menu using HTML & JSON data sources and AJAX loading. The jsTree is easily extendable, them-able and configurable. It has a built-in mobile theme for responsive design and various callback methods.

The jstree have many plugins for basic functionality like sort nodes,drag and drop nodes, context menu and search etc.

I am using the same database structure like the previous tutorial How to Create Dynamic Tree View Menu except for one extra link column was added in the table,

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,

How to create a tree menu using jstree and php

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 the tree.
  3. response.php: This file is used to fetch tree nodes from the database and convert them into JSON objects.

How To add href attribute in JSTree Node

I am using and extending Dynamic Tree with JSTree, PHP and MySQL tutorial, So I am not sharing the initial steps to create a tree using jstree, php and MySQL. I assumed you have understood my jstree menu previous article code.

Step 1: Add a new column link into database jstree table.

Step 2: Search unset($data[$key]); code in response.php file and put the below code like this.

Related Post
//added href attribut on each leaf node of jstree
  if(empty($item['children'])) {
      
        $item['a_attr']->href = 'http://goolge.com';
      }
     

     if($item['parent_id'] && isset($itemsByReference[$item['parent_id']])) {
        unset($data[$key]);
     }

Step 3: We need to bind the event on the leaf node so that the callback function will trigger on the click leaf node.

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

Now You can refresh the tree menu page and you will get href attribute added on each leaf node.

How To add href an attribute in JSTree and redirect on the link

So now we have added href attribute on each jstree nodes and we will redirect to that href link by clicking on jstree node.

<script type="text/javascript">
$(document).ready(function(){ 
    //fill data to tree  with AJAX call
    $('#tree-container').jstree({
    ......
    ....
    }).bind("select_node.jstree", function (e, data) {
       var href = data.node.a_attr.href;
     if(href == '#')
     return '';

       document.location.href = href;
  }); 
});
</script>

As you can see, I have used the JavaScript document.location.href method for redirecting on the link.

How To Display content on click of jstree node

I am assuming you have created the below div container on your page.

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

Above the right container div which will show your href content, You need to use the below code to show content on click of jstree node.

<script type="text/javascript">
$(document).ready(function(){ 
    //fill data to tree  with AJAX call
    $('#tree-container').jstree({
    ......
    ....
    }).bind("select_node.jstree", function (e, data) {
       var href = data.node.a_attr.href;
     if(href == '#')
     return '';

       $('#right-container').html(href);
  }); 
});
</script>

How to add search functionality in jstree

I am using jstree search plugin which will use to apply the search node on jstree container, You need to use the below code to show content on click of jstree node.

Step 1: Add search input field using the below HTML code,

<div class="col-sm-3"><input id="searchText" class="form-control input-sm" name="searchText" type="text" placeholder="Type to search..."></div>

Step 2: Added search plugin in jstree plugin list,

'plugins': ["wholerow", "types", "search"],

Step 3: Since we are calling search function in step 1 ,so we need to define search function which will call on keyup event of search input.

$( "#searchText" ).keyup(function() {
   var text = $(this).val();
   search(text)
      
});

function search(text){ 
            $('#tree-container').jstree(true).search(text);
        }

Conclusion:

We have learned how to add href attribute on each leaf node in jstree menu and redirect on link. We have also used search jstree plugin to add search functionality in treeview menu.

View Comments

  • Parvez bro, thank u so much for this post. Now how can I show any php file instead of that link
    "href = 'http://google.com' in response.php

          • Nice code ! Thanks...
            One big problem! When trying to modify your sql query ($sql = "SELECT * FROM `treeview_items1` ";) by adding a simple join ($sql = "SELECT a.*, b.* FROM `treeview_items1` a join table b USING (field) ";) everything just stops working.
            How can I change / expand the SQL syntax in the query string ?

          • hav u checked 'SELECT a.*, b.* FROM `treeview_items1` a join table b USING (field)' retuning same result as 'SELECT * FROM `treeview_items1'

  • Parvez - This code is great! How can I link just the parent to my database link field if it has no children?

  • You first need to find node has child if not then change this code line,
    bind("select_node.jstree", function (e, data) {
    var href ='#';
    var href = data.node.a_attr.href;
    var number_of_child = get_current_child_node;
    if(number_of_child <=0) {
    href = get_parent_node_href
    $('#right-container').html(href);
    } else {
    $('#right-container').html(href);
    }

    });

    • Thanks for the response! After posting, I realized that Parents and Children could both have links. I changed it to work like this and wanted to share in case someone else needs a similar solution.

      Index.php - Replace "Bind" event with "on Changed" event

      .on('changed.jstree', function (e, data) {
      var i, j, r = [];
      for(i = 0, j = data.selected.length; i &$item) {
      $item['a_attr']->href = &$item['link'];
      if($item['parent_id'] && isset($itemsByReference[$item['parent_id']])) {
      unset($data[$key]);
      }
      }

      • Man i love you :) you are awesome. You helped me a lot.
        i've been fighting with that over 6 hours, and then found your solution.

        Works really perfect! I would just want to add one small correction,
        if the varLink is NOT a child do not load/redirect to any page. That could avoid not needed problems.

  • Did my best to achieve that and its not working
    i'm trying to build an mlm script where each user sees his downline alone

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

4 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

10 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

10 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

10 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

11 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

11 months ago

Categories