I have a strange problem with JSTree and Ajax.
I generate my tree via an Ajax/PHP request which generates HTML (with UL,LI,A tags) using…
$.ajax({
url: 'ajaxTreeView.php?method=edit&partid='+partId,
cache: false,
success: function(tree)
{
$('#treeViewer').html(tree);
}});
and activate JStree on the code using…
options =
{
"core": { animation: 120 },
"themes": { theme: 'corral', dots: true },
"types":
{
"types":
{
"parent": { "icon": { "image": "images/custom/Legend/node_select.png" } },
"child": { "icon": { "image": "images/custom/Legend/node_select_child.png" } },
"current": { "icon": { "image": "images/custom/Legend/node.png" } }
}
},
"plugins": [ "html_data", "types", "themes", "ui", "contextmenu", "cookies" ],
"ui": { "select_limit" : 1 },
"cookies": { "save_selected" : false }
};
$("#tree").jstree(options);
I can’t seem to get a node to select easily. I tried initially_select but this doesn’t seem to work and also isn’t ideal as I often want to programatically select node anyway.
I tried using…
$('#tree').jstree("select_node", '#ref565', true);
This works if I call the function via a hyperlink but doesn’t work if I call it after I initalise JStree.
I see from adding an alert (all this happens in the Ajax Success routine)…
$('#treeViewer').html(tree);
$("#tree").jstree(options);
alert('test');
$('#tree').jstree("select_node", '#ref565', true);
… that the tree has not rendered before the alert kicks off.
I added a setTimeOut…
$('#treeViewer').html(tree);
$("#tree").jstree(options);
setTimeout(function() {selectNode(565);},1250);
$('#tree').jstree("select_node", '#ref565', true);
… this works.
I’m clearly being stupid. Am I using the wrong syntax? Why would I have to set a delay in order to select a node?
Please help.
If you want to initially select certain nodes after the tree loads, you are supposed to use the
initially_selectoption of the ui plugin. You said you tried it, but I don’t see it being used in the sample code you posted. Are you sure you are supplying correct IDs?To programmatically select nodes, you need to wait for the nodes you want to select to appear in the DOM first. Rather than using a timeout call back, I’m guessing it is more correct to bind to the
loaded.jstreeevent, which ought to be called after the tree has finished loading and all tree elements are in the DOM, and do your programmatic select in there.Example code showing usage: