Efficiently loading data using lazy loading in jsTree

I have been facing a challenge with dynamically loading the nodes of a jtree upon expansion. The limited documentation I could find is located towards the end of this specific page.

Several solutions involve creating nodes individually using a loop, similar to the approach discussed in this post. Although I haven't attempted it yet, based on the documentation, it seems like jstree should handle cycling through the nodes automatically.

Many suggestions recommend utilizing plugins: ["json_data"], however, the documentation for plugins does not mention this particular plugin. Could it be an outdated extension that is no longer necessary?

In my current implementation, I load the entire tree at once with the following code snippet:

$.ajax({
    var pn = $('#project_number').val();
    url : "bomtree?part=" + pn,
    success : function(tree_content) {
        var data = $.parseJSON(tree_content);
        var config = {
            'core' : {
                'data' : data
            }
        };
        $('#bom_tree').jstree(config);
    }
});

I have made adjustments to the code provided on the documentation page as shown below:

$(function() {
    var pn = $('#project_number').val();
    $('#tree').jstree({
        'core' : {
            'data' : {
                'url' : function(node) {
                    return '/doc/test2';
                },
                'data' : function(node) {
                    return {
                        'part' : node.id === '#' ? pn : node.id
                    };
                }
            }
        }
    });
});

The same json text functions perfectly with the initial code but throws an error with the revised code. As per the documentation,

The format remains the same as the above
, so I kept it consistent.

I also experimented with returning sample data matching the example provided:

[
       { "id" : "ajson1", "parent" : "#", "text" : "Simple root node" },
       { "id" : "ajson2", "parent" : "#", "text" : "Root node 2" },
       { "id" : "ajson3", "parent" : "ajson2", "text" : "Child 1" },
       { "id" : "ajson4", "parent" : "ajson2", "text" : "Child 2" }
]

However, regardless of the data used, jQuery consistently encounters a Sizzle.error at a specific line:

Sizzle.error = function( msg ) {
    throw new Error( "Syntax error, unrecognized expression: " + msg );
};

What could possibly be causing this issue?

Answer №1

According to the jstree documentation, if you set children to boolean true when using AJAX in jsTree, the node will render as closed and trigger an additional request for that node when opened, which may be exactly what you need. You can find more information on this feature here.

Answer №2

Expanding on Nathan's response with a simplified illustration: an example of a tree demonstration utilizing lazy loading.

JavaScript:

$('#the_tree').jstree({
    'core' : {
        'data' : {
            'url' : "tree/ajax.php", 
              'data' : function (node) {
                  return { 'id' : node.id };
              }
        }
    },

});

PHP:

header('Content-Type: application/json');

if ( $_GET["id"] === "#" ) { 
    $data = array(
            array( "id" => "ajson1", "parent" => "#", "text" => "Simple root node"  ),
            array( "id" => "ajson2", "parent" => "#", "text" => "Root node 2", "children" => true ),

    );
}

else if ( $_GET["id"] === "ajson2" ) {
    $data = array(
        array( "id" => "ajson3", "parent" => "ajson2", "text" => "Child 1" ),
        array( "id" => "ajson4", "parent" => "ajson2", "text" => "Child 2" )
    );
}

echo json_encode( $data);

Only nodes marked with "children" : true will trigger a request for child nodes upon opening, while other nodes are considered leaf nodes.

Answer №3

The documentation/examples may be a bit challenging to navigate. It's worth mentioning that the root cause of your confusion stems from a significant upgrade - the previous version is quite different from the current one, leading to inconsistencies in the examples provided.

The upside is that lazy loading is readily supported, albeit not immediately apparent. The key lies in the fact that the data: configuration is invoked as each node expands. However, for this feature to function correctly, the URL function must generate distinct URLs for each node. In the snippet below, take note of the conditional statement to specify the URL based on whether the node is root (#) or not.

$('#TreeDiv')
  .jstree({
    core: {
      data: {
        url: function (node) {
          return node.id === '#' ? '/UserAccount/AccountGroupPermissions' 
                                 : '/UserAccount/AccountPermissions/' + node.id;
        },
        type: 'POST'
      }
   },
   plugins : ["checkbox"]
});

Answer №4

If you want to implement lazy loading, your backend must provide a JSON object with tree nodes that include a children property field. The children property should either contain child elements or a boolean value of true (array or boolean). It is recommended to handle this logic on the frontend if you are using a strongly typed language on your backend. Here is an example of an AJAX success callback:

$('#tree').jstree({
    'core' : {
        'data' : {
            'url' : function(node) {
                return '/doc/test2';
            },
            'data' : function(node) {
                return {
                    'part' : node.id === '#' ? pn : node.id
                };
            },
            'success' : function(nodes) {

                var validateChildrenArray = function(node) {

                    if (!node.children || node.children.length === 0) {
                        node.children = true;
                    }
                    else {
                        for (var i = 0; i < node.children.length; i++) {
                            validateChildrenArray(node.children[i]);
                        }
                    }
                };

                for (var i = 0; i < nodes.length; i++) {
                    validateChildrenArray(nodes[i]);
                }
            }
        }
    }
});

Implementing this approach will allow you to effectively lazy load your tree structure.

Answer №5

By cleverly combining the "select_node.jstree" event with the "create_node" method, I was able to create my own customized lazy loading solution. Whenever a node is selected, the event handler verifies if there are any children and then dynamically adds the server's response to each selected node one by one. The server's response didn't match the typical requirements of jstree, but this unique approach ended up saving me a significant amount of time and effort. Hopefully, this technique can be beneficial for others facing similar challenges.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Exploring the possibilities of cakePHP in integrating Ajax

After setting $this->layout = 'ajax', Cake still requires the view file for that action to be present. I'm wondering, is it necessary to create that view file, or is there a workaround? I want to avoid having one-liner view files for aja ...

transform a JSON file containing multiple keys into a single pandas DataFrame

I am trying to convert a JSON file into a DataFrame using json_normalize("key_name"). I have successfully converted one key into a DataFrame, but now I need to convert all keys into one single DataFrame. { "dlg-00a7a82b": [ { "ut ...

Working with the visibility of a button using JavaScript

My goal is to toggle the visibility of a button using JavaScript. Initially, on page load, the button should be hidden. function hideButton(){ var x = document.getElementById('myDIV'); x.style.display = 'none'; } The visibilit ...

Issues with Recursive Ajax Functionality in Internet Explorer 11

Trying to perform consecutive ajax GET calls using the $.ajax jQuery method in order to handle a large JSON data size of around 2MB. The process runs smoothly in Chrome, but encounters issues in IE11. In IE11, it consistently falls into the fail method dur ...

Error message for something that is conceptualized as an unexpected mistake in a sector unrelated to J

https://i.stack.imgur.com/FBmia.png Whenever I try to run the following code snippet, I encounter an error: var request = 'randomcode'; $.post('../php/forms/postrequest.php', 'type=' + request, function (response) { var ...

Verifying WordPress slug existence using AJAX

I want to verify if a slug URL already exists using the user interface. My initial idea was to use an AJAX solution similar to this. `jQuery("#slugBrut").keyup(function() { var slugBrutText = jQuery("#slugBrut").val() ; ...

Using jQuery, you can easily modify the color of a TD cell by applying the css properties assigned to the div element

I am attempting to implement a jQuery script that will execute upon the loading of the document. The objective is for the script to retrieve the background color of a div located within a td cell and apply it as the background color for the respective td c ...

Run a Javascript function two seconds after initiating

My goal is to implement a delay in JavaScript using either setInterval or setTimeout, but I am facing an issue where the primary element is getting removed. Code that works fine without Javascript delay: const selectAllWithAttributeAdStatus = document. ...

Revoke the prior invocation of the Google Maps geocoding function

While working on implementing an autocomplete with JavaScript and the Google Maps geocode method (using the keyup event on input), I have encountered a problem where I sometimes receive the results of the previous search instead of the current one. I am l ...

Working with JSON Strings using moshi and retrofit2

The API I am currently utilizing responds with a JSON object nested inside a list structure: [ { "name": "Seattle", "lat": 47.6038321, "lon": -122.3300624, "country": &qu ...

Is there a way to make a server call in Nodejs Express without using ajax or refreshing the page?

Currently, I am in the process of implementing MongoDB save functionality by submitting a form. My goal is to showcase the results obtained from the server without having to refresh the page. While I can accomplish this using $.(ajax), it presents a limita ...

ways to halt a noise once an animation is complete

I don't have much experience with coding in general, but somehow I've made it this far. Now I'm stuck on the final piece of the puzzle. This is related to a Twitch alert that I'm setting up through 'Stream Elements'. The iss ...

using database URL as an AJAX parameter

I am currently working on a Python CherryPy controller that needs to validate a database URL by attempting a connection. However, I am facing challenges with passing the parameter to the method. Below is my AJAX call: $.ajax({ async: false, ty ...

JQuery ID Media Queries: Enhancing responsive design with targeted

Is it possible to integrate a media query into the selection of an ID using JQuery? For example: $('#idname') $('@media (max-width: 767px) { #idname }') In essence, can you target the #idname with that specified media query in JQuery ...

Having difficulty deciphering the JSON data

I am a novice in Android development and I have a question about how to fetch and display JSON data from . Specifically, I want to show the USD value for each category in a text box on the main activity. When I try to log the USD values, it shows 210 for ...

Express.js redirection not refreshing Jade HTML content

I'm currently facing an issue with displaying a flash message in Express.js using Jade's templating engine and connect-flash. My goal is to show an error message when a user tries to add a new User object to the database that already exists. Howe ...

A Beginner's Guide to Duplicating Bootstrap Containers in Jade

I am working with JSON data that is being transmitted from an Express and Mongoose Stack to be displayed on the user interface created in Jade. I am wondering which Jade Construct I should use to loop through a Bootstrap Container of col-md-4 using Jade s ...

What is the best way to toggle the active class on a ul list?

After clicking, the active class remains on the original "li" instead of changing as it should. I've tried modifying the code but haven't been able to find a solution. Can someone please review what I might have missed? It seems like there's ...

Performing an Ajax post request to a PHP script in order to retrieve a PHP variable using XMLHttpRequest

I am looking to dynamically update my table using JavaScript every few seconds. Currently, I have set up an AJAX post request to my update.php file and trigger it if it is set. Then, I execute a MySQL query to retrieve the data and store the resultset in ...

Tips for presenting the retrieved data from the database in a user-friendly format

$ //First step involves running the PHP code that executes the SQL query to retrieve data from the database, storing it in get_row1, and sending it as a response to Ajax$ <?php $connect = mysql_connect("localhost", "root", ""); $data = mysq ...