NayNes NayNes - 10 months ago 80
Ajax Question

JsTree Selection is getting reversed

So my problem is that, basically, I set some nodes in JsTree and it works on the one tree I already have on my page, but those that get loaded dynamically just revert the selection. That means that they do get selected as intended but then get deselected afterwards, for some reason.

Code for selection:

if(element !== null)
$(value).parent().find(".filter-value-tree").jstree("select_node", "#"+element);

And the line of code in jquery-2.1.1.js:

return typeof n !== U && n.event.triggered !== b.type ? n.event.dispatch.apply(a, arguments) : void 0

Before that specific line the nodes are selected just as intended.

A snippet to show the basics of what I am trying to do (it now reproduces the problem, seemingly):

$("#testBtn").on("click", function() {

$("#filter-value-tree").jstree("select_node", "#2");

function loadTree(callback){
//Normally there would be a ajax request here, to be used with differenct callback functions
var response = '<li id="1">Information</li><li id="2">Service</li><li id="3">Claim</li><li id="4">Education</li>';

}, 1000);

function getValueTree(result){
$("#testDiv").append("<div id='filter-value-tree'><ul><li id='1'>Test1</li><li id='2'>Test2</li></ul></div>");


'core' : {
'check_callback': true,
'multiple': true
"plugins" : [ "changed" ]

<script src=""></script>
<script src=""></script>
<link rel="stylesheet" href="" />

<button type="button" id="testBtn">Test</button>

<div id="testDiv"></div>

To end it, some more information, I am loading the content of the jstree with AJAX from a php page from my mysql database. The ajax call is set to async: false, just if some wondered if it could be that. The loading works as intended and I just want to say that the nodes ARE being selected, but are just being deselected after some time (if I step through with debugging at that line from jquery-2.1.1.js, so the last thing before the debugger finishes).

I hope you can help me, thanks in advance.


The problem you face relates to synchronous/asynchronous code:

In this code:

$("#filter-value-tree").jstree("select_node", "#2"); 

... the last statement is executed before getValueTree is called. This is because loadTree will perform the Ajax call, but will return immediately without calling the callback. The callback is only called when the response will come in via an asynchronous event. This event will never be processed before your current code has completed running (i.e. has emptied the call stack). Only then events in the queue are processed.

To solve this, move that statement into the callback part, for instance, as follows:

loadTree(function () {
    $("#filter-value-tree").jstree("select_node", "#2");