Nazkter Nazkter - 3 months ago 29
Javascript Question

jsTree: Get new tree JSON every time I drop a node

I'm using jsTree to create two tables of content (A and B), I move nodes from A to B and I want to get the json of the tree B to save it in database every time I drop a node in the tree B, but when I get the json on the drop event, it only get the json without the new node.

I need to get the tree with the new node included . I get the json in the event "dnd_stop.vakata" with this code:

$(document).on('dnd_stop.vakata', function (e, data) {
var json = $("#JSTreeTOC").jstree(true).get_json();
console.log(JSON.stringify(json));
// Here I want to make an AJAX call to save the tree in database
});


Addicionally, this is my code for the jstree creation:

//jsTree "A":
$('#JSTreeServicios').jstree({
'core': {
"check_callback": false,
'data': tree
},
"dnd": {
"always_copy": true,
},
"plugins": ["dnd", "search", "types", "contextmenu", "sort"]
});


//jsTree "B":
$('#JSTreeTOC').jstree({
'core': {
"check_callback": true,
'data': tree
},
"plugins": ["dnd", "search", "types", "sort", "contextmenu"]
});

Answer

After some time I realized that the jsTree was not being updated right at the time when the "dnd_stop.vakata" event runs, it happens a few milliseconds later, to solve the problem on localhost I added the following lines:

$(document).on('dnd_stop.vakata', function (e, data) {
    setTimeout(function(){
        var json = $("#JSTreeTOC").jstree(true).get_json();
        console.log(JSON.stringify(json));
        // Here I make an AJAX call to save the tree in database
    }, 100);
});
Comments