How to show selected nodes of a tree - JSTree jQuery - javascript

I want to show the records in a tree format for which I used JStree plugin of jQuery.
I have successfully implemented the JStree to show records as tree, but I am having issue when a user selects the nodes from the tree for that I also want to show selected nodes as a tree for better representation .. but the code doesn't seems to work perfectly..
Code below renders the tree:
$.ajax({
url: "<?php echo base_url(); ?>Controller_Name/Function_Name",
type: "POST",
data: "code="+code,
success: function(result)
{
$('#jstree').jstree("destroy");
$('#jstree').jstree({
'checkbox': {
three_state: true
},
'plugins': ['search', 'checkbox', 'wholerow'],
'core': {
'data': JSON.parse(result),
'animation': false,
'themes': {
'icons': false,
}
},
'search': {
'show_only_matches': true,
'show_only_matches_children': true
}
});
}
});
I want to show the selected nodes as a tree using the same JStree plugin..
this below code is the one which should give the tree of selected nodes..
$('#jstree').on('changed.jstree', function (e, data){
var objects = data.instance.get_selected(true)
var leaves = $.grep(objects, function (o)
{
return data.instance.is_leaf(e)
})
console.log(leaves);
var json = [];
$.each(leaves, function (i, o){
district_ids();
json.push({"id":o.id, "parent":o.parent, "text":o.text});
});
console.log(json);
$.ajax({
success: function(json){
$('#output').jstree("destroy");
$('#output').jstree({
'plugins': ['wholerow'],
'core': {
'data': json,
//'data': json,
},
});
}
});
});
but the function does not gives the desired result... it keeps loading

Related

Reload DATATABLE inside AJAX success without refreshing page

I have a table using Datatable plugin. I have filtered what I want to delete and after deletion, I manage to empty the value.
After that, if I want to filter using the same text again, for example, I have ba 1 and ba 2 and after deleting ba 1, it still shows the cell when I entered ba on the filter textarea field. It suppose to display the remaining ba which are not deleted yet.
For your information, I'm not using built in Datatable Ajax method.
what I'm trying to do is I want it to reload the table with the new data without refreshing the page after ajax on success. How to do that?
My datatable :
var table1 = $('#table1').DataTable(
{
pageLength : 500,
lengthChange: false,
deferRender: true,
scrollY: 800,
scrollCollapse: true,
scrollX: true,
bSort: false,
cache: true,
autoWidth: false,
columnDefs: [
{
targets: 0,
checkboxes:
{
selectRow: true
}
}
],
select: {
style: 'multi',
selector: 'td:not(:nth-child(4), :nth-child(5), :nth-child(6), :nth-child(9), :nth-child(10), :nth-child(13), :nth-child(14), :nth-child(15), :nth-child(16), :nth-child(17), :nth-child(18), :nth-child(19), :nth-child(20), :nth-child(21), :nth-child(22), :nth-child(23), :nth-child(24), :nth-child(25))'
}
});
Here's my filtering function code :
table1.columns().every(function ()
{
var table = this;
$('.filter', this.header()).on('keyup change', delay(function (settings, data, dataIndex)
{
if (table.search() !== this.value)
{
table.search(this.value).draw();
}
}, 500));
});
Here's my AJAX success code for deletion based on selected checkbox:
$('.btnN2').click(function(){
var answer = confirm('Delete N2 : Are you sure you want to delete selected items?');
if (answer)
{
console.log('yes');
var rows = $(table1.rows({selected: true}).$('input[type="checkbox"]').map(function()
{
return $(this).prop("checked") ? $(this).closest('tr').attr('data-getstockcode') : null;
}));
var getstockcodes = [];
$.each(rows, function(index, rowId)
{
console.log(rowId)
getstockcodes.push(rowId);
});
$.ajax({
url: 'del_n2',
type: 'GET',
data: {"getstockcodes": JSON.stringify(getstockcodes)},
dataType: 'JSON',
success:function(data){
console.log(data);
$(table1.rows({selected: true}).$('input[type="checkbox"]').map(function()
{
if($(this).prop("checked"))
{
$(this).parents("tr:eq(0)").find(".note2").val('');
console.log('reset');
}
}));
}
});
}
else
{
console.log('cancel');
}
});
Here's my insert data based on keyup event
$(".note2").keyup(delay(function()
{
var stockcode = $(this).data("stockcode");
var stockname = $(this).data("stockname");
var value = $(this).val().replace(/(\r\n|\n)/g, "\\n");
$.ajax({
url: 'saveNote2',
type: 'GET',
data: 'stockcode='+stockcode+'&stockname='+stockname+'&value='+value,
dataType: 'JSON',
success: function(data){
console.log(data);
},
error: function(data){
console.log(data);
}
});
}, 300));
Just add this in your success function
table1.ajax.reload()
If you are using ajax datatable or local you need to make it like this
table1.clear();
table1.rows.add(your response data array);
table1.draw()

Drag JSTree Node into an external div

I am using Jquery jsTree where i load my data into jstree with json. Below is my code to populate my jsTree
$.ajax({
async: true,
type: "POST",
url: "MasterPageDataService.asmx/GetAllSites",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (jsonData) {
$("#divSitesTree").jstree({
'core': {
'data': jsonData
},
"plugins": ['dnd', "themes", "json_data", "ui"]
});},
});
I get the data populated perfectly.
Now i want to drag a node and drop it onto div element. I have made my div drop able to serve the purpose like this
$(".droppable").droppable({
drop: function (event, ui) {
alert('dropped');
// here i want the id of dropped node
}
});
I don't want to move the node from tree to anywhere , i just want to get the id of the node being dragged and dropped into div. But my problem is that m not even getting the drop event getting fired. e.g i don't get any alert at all.
I have googled the different solutions and tried this so far.
<script>
$(function () {
$('.drag')
.on('mousedown', function (e) {
return $.vakata.dnd.start(e, { 'jstree': true, 'obj': $(this), 'nodes': [{ id: true, text: $(this).text() }] }, '<div id="jstree-dnd" class="jstree-default"><i class="jstree-icon jstree-er"></i>' + $(this).text() + '</div>');
});
$(document)
.on('dnd_move.vakata', function (e, data) {
var t = $(data.event.target);
if (!t.closest('.jstree').length) {
if (t.closest('.drop').length) {
data.helper.find('.jstree-icon').removeClass('jstree-er').addClass('jstree-ok');
}
else {
data.helper.find('.jstree-icon').removeClass('jstree-ok').addClass('jstree-er');
}
}
})
.on('dnd_stop.vakata', function (e, data) {
var t = $(data.event.target);
if (!t.closest('.jstree').length) {
if (t.closest('.drop').length) {
$(data.element).clone().appendTo(t.closest('.drop'));
}
}
});
});
</script>
But what it does, it simply appends the node(icon+text) in my div. But that is not what i want. I just want to get the Id of the node inside an event where i can perform further operation based over the id of the node.
How do I accomplish this task with jsTree? Please Help.
Luckily I have found the solution. Below is the script to get the id of the node being dragged and the id of the target where the node is being dropped
$(document)
.on('dnd_stop.vakata', function (e, data) {
var t = $(data.event.target);
if (!t.closest('.jstree').length) {
if (t.closest('.drop').length) {
alert(data.data.origin.get_node(data.element).id);//node id
alert(data.event.target.id) //target id
}}});});

select2 programmatically without knowing results in advance

I am trying to write a test for a Javascript select2 control and I would like to automatically select the first item. Since it's using ajax I do not know what the first item is. All the examples I have seen create <option> however they assume knowledge of the value. How can I select the first item without knowledge? (Note this example only runs the ajax command after 3 items are entered).
var $selector = $("#foo");
$selector.show().select2({
allowClear: true,
placeholder: "--------",
minimumInputLength: 3,
ajax: {
url: "...",
type: 'GET',
dataType: 'json',
delay: 250,
data: function(term, page) {
return {
number__icontains: term
};
},
results: function(data) {
return {
results: $.map(data.objects, function(option) {
return {
'id': option.id,
'text': option.desc
};
})
};
},
cache: false
},
initSelection: function(element, callback) {
...
}
});

JStree Async Search

Whe are busy building a web based app. And we inherited the code where the previous developers used jstree so now the whole site consist out of a tree that uses jstree.
Everything worked even the search on the tree, but then we came across a problem where certain tabs loaded too long because of the tree which was too big.
So we went and made the the tree async / lazy loading which works perfectly but know the problem is that the search doesn't work that well.
Because we made a api for the search which works but it doesn't do the call back after new tree has been loaded.
Can someone help because I've been struggling for 3 days now and its giving me a head ache.
// Tree Search
searchAjaxFunction: function () {
var TreeCustomApiRequest = {
nTreeCustomDesc: document.getElementById("tree_search").value,
nUserId: document.getElementById("TrendUserID").value,
nAccessLevel: document.getElementById("hfTrendAccessLevel").value
}
$.ajax({
type: "POST",
data: JSON.stringify(TreeCustomApiRequest),
url: 'api/TreeCustomSearch.aspx',
success: function (jsonData)
{
Tree.dataJson = jsonData;
// Clear the tree.
//Tree.dataJson = jsonData;
if ($("#tree").jstree()) {
$('#tree').jstree(true).settings.core.data = jsonData;
$('#tree').jstree(true).deselect_node(this);
$('#tree').jstree(true).toggle_node(this);
$('#tree').jstree(true).refresh();
}
},
contentType: "application/json"
});
},
onClickFunctionNode: function(node) {
Tree.treeDivIdSelector.jstree(true).toggle_node(node);
},
pluginsArray: ["search", "checkbox", "types", "json_data","html_data"],
treeMenuContextItems: {},
Init: function(initData) {
Tree.dataJson = initData.dataJson;
Tree.treeDivIdSelector = initData.chartDivId;
Tree.searchDivIdSelector = initData.searchDivId;
var apiUriTree = 'api/TreeCustomChildren.aspx';
Tree.treeDivIdSelector.jstree({
"checkbox": {
"keep_selected_style": true,
"three_state": false
},
"plugins": Tree.pluginsArray,
'core': {
'data': function (node, cb) {
// Fetch tree custom parent nodes
if (node.id === "#") {
cb(Tree.dataJson);
}
else {
var _cb = cb;
//Fetch tree custom Child nodes
var TreeCustomApiRequest = {
nUserId: document.getElementById("TrendUserID").value,
nAccessLevel: document.getElementById("hfTrendAccessLevel").value,
nTreeCustomParentId: node.id
}
function recieveData(data) {
cb(data);
}
$.ajax({
type: "POST",
data: JSON.stringify(TreeCustomApiRequest),
url: apiUriTree,
success: recieveData,
contentType: "application/json"
});
}
},
"themes": {
"icons": false
}
},
"contextmenu": {
items: Tree.pluginsArray.indexOf("contextmenu") > -1 ? Tree.treeMenuContextItems : null
}
});
var tree = Tree.treeDivIdSelector.jstree();
function getNode(sNodeID) {
return tree.get_node(sNodeID);
}
Tree.treeDivIdSelector.on('click', '.jstree-anchor', function(e) {
Tree.onClickFunctionNode(this);
}
);
//Tree.searchDivIdSelector.keyup(Tree.searchFunction);
},
The next code is in the client side......
<script type="text/javascript">
$(document).ready(function () {
var dataJson = <%=sTreeViewJson%>
Tree.Init({ dataJson: dataJson, chartDivId: $("#tree") });
$("#btnSearch").click(function () {
// Do the Ajax search
Tree.searchAjaxFunction();
//var value = document.getElementById("tree_search").value;
//Tree.searchFunction();
})
});
</script>
Thank you Nikolay, it was a stupid mistake from me so what I added was just this to my code:
success: function (jsonData, callback )
{
//Goes back to the Callback with the new search data
Tree.Init({ dataJson: jsonData, chartDivId: $("#tree"), searchDivId: $("#tree_search") });
$('#tree').jstree(true).refresh();
}
So I removed the
$('#tree').jstree(true).settings.core.data = jsonData;
$('#tree').jstree(true).deselect_node(this);
$('#tree').jstree(true).toggle_node(this);
Know it gets my data and refreshes the table with the init function while it has my new data.
Hope this also may help someone = ).

$tree.tree is not a function

I am generating a tree in plone using an add-on product called collective.virtualtreecategories . However, I keep getting a weird javascript error and the tree cannot be displayed.
On my browser's error console, I get the following:
$tree.tree is not a function
Here is the part of code that produces the error:
$tree.tree({
data: {
type: "json",
url: "##vtc-categories-tree.json",
async: false
},
lang: {
new_node: "New category"
},
rules: {
deletable: ["folder"],
renameable: ["folder"],
draggable: "none",
droppable: "none",
},
callback: {
beforechange: function(node, tree_obj) {
return before_change_node()
},
onselect: function(node, tree_obj) {
node_selected(node)
},
oncreate: function(node) {
jq(node).attr('rel', 'folder')
},
onrename: function(node, lang, tree_obj, rb) {
old_id = node.id // may be undefined (new node)
new_name = jq(node).children("a:visible").text();
// shared code. Server determines if creating/renaming by the old_name value
jq.ajax({
type: 'POST',
url: "vtc-category-added-renamed",
data: {
'category_path': selected_category(node),
'old_id': old_id,
'new_name': new_name
},
success: function(data) {
jq.jGrowl(data.msg, {
life: 1500
});
// set/change node id
if (data.result) {
node.id = data.new_id
}
},
dataType: 'json',
traditional: true
})
},
beforedelete: function(node, tree_obj) {
jq.ajax({
type: 'POST',
url: "vtc-category-removed",
data: {
'category_path': selected_category(node)
},
success: function(data) {
jq.jGrowl(data.msg, {
life: 3000
});
},
dataType: 'json',
traditional: true
});
return true;
}
}
});​
The complete code listing can be found HERE
Can someone help me fix this?
UPDATE:
I should perhaps add that, this was working before in a different setting. Now, I just recreated the project and thats when I got this error.
As far as I can tell from your code $tree isn't a function, its an element
on line 89 var $tree = jq('ul#VTCTree');
therefore I assume .tree() is a JQuery widget and isn't working as expected?
Just seen some of the comments and the updates. Have you checked the path/file inclusion of the tree plugin/widget?
On my browser's error console, I get the following:
if your browser is Internet Explorer, the extra comma that you have here
droppable: "none",
is a widely known problem.
Not a problem for Firefox, but will give unexpected results, like 3 elements in the following array. but length = 4
myArr = [1,2,3,,]
also, check this https://stackoverflow.com/a/5139232/982924
I had the same issue, even though I had jquery loaded and the jquery.filetree.min plugin loaded. I was missing the jquery UI js which is also required.

Categories

Resources