Search code examples
jqueryajaxfancytree

Reload entire Fancytree


I have a combobox with different options that each brings up a fancytree to the screen.

I make an ajax call to get the source for the fancytree but it's not reloading and shows the same options again and again.

part of the code:

$.ajax({
 url: "get_treedata.php",
 type: "POST",
 data: {
       id: id
       },
 success: function(json){
   console.log(json);

    var mynodes = JSON.parse(json);
    $('#t-board').fancytree( // t-board is my div container
       {
          source: mynodes,
          ... // my other options
    });
  }
});

that code is inside a function that I call in the "onchange" of my combobox. Tell me what you think, and if I need to be more specific or something.

Thanks in advance.


Solution

  • You can not re-initialize the tree. But you can update the tree options or reload it with new source option.

    • Reload the tree with new source option

      var treeOptions = {...}; // initial options
      $('#t-board').fancytree(treeOptions);
      $('#combobox').change(function () {
      var id = $('option:selected', this).val();
      
        var newSourceOption = {
          url: 'get_treedata.php',
          type: 'POST',
          data: {
            id: id
          },
          dataType: 'json'
        };
      
        var tree = $('#t-board').fancytree('getTree');
        tree.reload(newSourceOption);
      });
      
    • Add or replace other tree options

      var treeOptions0 = {...}; // initial options
      var treeOptions1 = {...}; // other tree options
      var treeOptions2 = {...};
      $('#t-board').fancytree(treeOptions0);
      $('#combobox').change(function () {
      
        var id = $('option:selected', this).val();
      
        if(id === '1'){
          $('#t-board').fancytree('option', 'selectMode', treeOptions1.selectMode);
          $('#t-board').fancytree('option', 'renderNode', treeOptions1.renderNode);
          $('#t-board').fancytree('option', 'icons', treeOptions1.icons);
          //...
        }else if(id === '2'){
          $('#t-board').fancytree('option', 'selectMode', treeOptions2.selectMode);
          $('#t-board').fancytree('option', 'renderNode', treeOptions2.renderNode);
          $('#t-board').fancytree('option', 'icons', treeOptions2.icons);
          //...
        }
      });