Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refresh a jsTree with new JSON data?

I have a file upload element that scans the file names upon change and does something to get a valid treeJSON variable. When the function detects a change the second time, the treeJSON variable will update, and I need to update the tree.

I've tried various methods such as refresh(), destroy() etc., but I haven't been able to construct a new tree on the same page without reloading the page. Here is a snippet, I've included all the functions and it works. The important part is working with the treeJSON

input.onchange = function (e) {
  // do something
};
var treeJSON = someVar;

$("#tree").jstree({
  core: {
    check_callback: true,
    data: treeJSON,
  },
});

1 Answers

You only have to tell jstree once where to load the root (core.data) . On refresh the tree will re-populate based on this content.

I would do this:

var treeJSON = 'originaltree';

input.onchange = function (e) {
    // something
    treeJSON = $.parseJSON(newtree); // if newtree is json
    var tree = $('#tree').jstree(true);
    tree.refresh();
}

$('#tree').jstree({
    'core': {
        'check_callback': true,
        'data':  treeJSON
    }
});

Or if you want to be even more specific based on which node:

$('#tree').jstree({
    'core': {
        'check_callback': true,
        'data': function (node, cb) {
            if (node.id === '#') { //Load root, will fire on first load as well as on refresh
                cb.call(this, treeJSON);
            }
        }

    }
});
like image 116
Cat Avatar answered Dec 01 '25 02:12

Cat