Populating JsTree with JSON variable - javascript

I've been trying the whole day to get this thing working but somehow JsTree doesn't want to render my JSON data.
Here is the example JSON object:
{"parent":null, "ProductOption":null, "data":"HlaHd", "text":"global", "DelegationScope":0, "children":null, "entityId":1}
I get the JSON object through an AJAX call on $(document).ready():
if ($('#ProductTree').length) {
$.ajax({
type: "Post",
url: "/blah/blah",
dataType: "json",
data: { id : blah },
success: function (json) {
createJsTree(json);
}
});
}
And here is how I'm creating the tree:
function createJsTree(json) {
$('#ProductTree').jstree({
'core': {
'themes': {
'name': 'proton',
'responsive': true
},
'check_callback': true,
'data': json
}
});
}
At first I thought maybe my JSON object is faulty, so I printed the object on the chrome's console right before creating the JsTree:
function createJsTree(json) {
console.log(json);
$('#ProductTree').jstree({
'core': {
'themes': {
'name': 'proton',
'responsive': true
},
'check_callback': true,
'data': json
}
});
}
And the JSON object is exactly as I stated above. Now the funny thing is, if I just paste the literal JSON object as the data in JsTree creation like the following:
function createJsTree(json) {
$('#ProductTree').jstree({
'core': {
'themes': {
'name': 'proton',
'responsive': true
},
'check_callback': true,
'data': { "parent": null, "ProductOption": null, "data": "HlaHd", "text": "global", "DelegationScope": 0, "children": null, "entityId": 1 }
}
});
}
Then the tree gets rendered. What on earth is going on here?

It looks like you are trying to pass a string representing a json object instead of the object itself. It should work if you write data: JSON.parse(json) replacing data: json.

You need to parse responded JSON string to json format using JSON.parse().
Hope this will help.

Related

Unable to map array of object into jQuery autocomplete

I am adding the jQuery Autocomplete plugin to my project. I have a source value which is an array of objects (from a mySQL database). I am unable to map them into desired format of autocomplete.
This is the data want to map:
[{
"value": "730",
"label": "iPhone"
}, {
"value": "731",
"label": "Screen Protector"
}, {
"value": "732",
"label": "Maxboost"
}, {
"value": "733",
"label": "JETech"
}, {
"value": "734",
"label": "Mr Shield"
}]
$("#product_one").autocomplete({
source: $.ajax({
type: "GET",
url: "/wp-json/product/product-info/",
success: function(res) {
$.each(res, function(key, val) {
return {
"label": val.label,
"value": val.value
}
});
}
});
});
Any suggestion or modification of question would be appreciated.
The issue is because you're providing source with a jqXHR object, not an array, string or function as it expects (docs)
Given the use of AJAX, it would make the most sense for you to use provide a function which uses the request and response arguments. Also note that as the data you retrieve is already in the correct format (ie. an array of objects with label and value properties), you can provide it directly to response() without needing to loop through it. Try this:
$("#product_one").autocomplete({
source: function(request, response) {
$.ajax({
type: "GET",
url: "/wp-json/product/product-info/",
success: function(data) {
response(data);
}
});
}
});
You should first load your data and then set them as the source of the autocomplete.
$.ajax({
type:"GET",
url: "/wp-json/product/product-info/",
success:function(res){
//Based on your object creation, it looks that you can directly use the response
$( "#product_one" ).autocomplete(res);
}
});

Select2 won't load remote json response

I have an API that is called by Select2 (v4.0.5) however the debug message in the console says:
Select2: The AJAX results did not return an array in the results key of the response.
When I review the documentation at Select2's documentation site I seem to be following it correctly. This is the javascript I use on the webpage:
$('#account_id').select2({
debug: true,
minimumInputLength: 3,
dataType: 'json',
ajax: {
url: '/api/account-query',
data: function (params) {
var query = {
search: params.term,
v: "new"
}
return query;
},
}
});
This is the response from the API (sensitive bits redacted):
{
"results": [{
"id": "redacted-1",
"text": "text redacted 1"
},{
"id": "redacted-2",
"text": "text redacted 2"
},{
"id": "redacted-3",
"text": "text redacted 3"
},{
"id": "redacted-4",
"text": "text redacted 4"
},{
"id": "redacted-5",
"text": "text redacted 5"
}]
}
If I take the select2 code and supply it with the static json response (without results prepended, just the array) it works just fine.
What am I missing?
Thanks!
You have to provide the processResults callback function so Select2 able to render result in proper way.
I have created a jsfiddle (https://jsfiddle.net/shcavbng/) demo that doing the same.
$('#account_id').select2({
debug: true,
minimumInputLength: 3,
dataType: 'json',
ajax: {
url: 'https://reqres.in/api/users',
data: function (params) {
console.log('params =>' , params);
var query = {
search: params.term,
v: "new"
}
return query;
},
processResults: function (data) {
console.log('results =>' , data);
data = data.data.reduce(function(o,i){o.push({id:i.id,text:i.first_name});return o;},[]);
console.log('results =>' , data);
return {
results: data
};
}
}
});
I figured it out, and as expected I was overlooking a simple aspect:
Content-Type header needed to be application/json vs text/html

Select2 with JSON data serialized from Django

I have data in JSON created by Django serialization.
I use the example:
Select2 Loading remote data but still I getting information in a field that nothing found.
What should change to select2 work with data generated by Django?
JSON Data:
[{
"fields": {
"sku": "8"
},
"model": "catalog.product",
"pk": 8
},{
"fields": {
"sku": "9"
},
"model": "catalog.product",
"pk": 9
}]
Html:
<select class="js-data-example-ajax"><option value="3620194" selected="selected">select2/select2</option></select>
JavaScript:
$('.js-data-example-ajax').select2({
ajax: {
url: "{% url 'catalog.views.product_sku_json' %}",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
});
Answer by kevin-brown on github:
You are going to need to re-map your results to have id and text keys.
https://select2.github.io/announcements-4.0.html#changed-id
And it works thanks Kevin!

invalid character javascript error while using JSON.parse

I am trying to convert a json string to object format read from a .js file.
Below is the JSON string in document.js
[
{
"type": "TableShape",
"id": "63c0f27a-716e-804c-6873-cd99b945b63f",
"x": 80,
"y": 59,
"width": 99,
"height": 107,
"name": "Group",
"entities": [
{
"text": "id",
"id": "49be7d78-4dcf-38ab-3733-b4108701f1"
},
{
"text": "employee_fk",
"id": "49be7d78-4dcf-38ab-3733-b4108701fce4"
}
]
}
];
now i am calling the document.js in window load using AJAX like below
$(window).load(function () {
$.ajax({
url: "JS/Draw2d/SampleData/document.js",
async: false,
success: function (result) {
debugger;
jsonStringFromServer = JSON.parse(result);//Here Javascript error stating invalid character
alert(jsonStringFromServer);
}
});
});
When the $.ajax function receives JSON, it automatically deserialises it for you. The error you're seeing is being cause because you're passing an object to JSON.parse, not a JSON formatted string - you don't need to use JSON.parse at all. Try this:
success: function (result) {
debugger;
console.log(result); // = the received object
}
I would also strongly suggest you remove async: false as it is extremely bad practice to use it.

How to get jstree to work properly with ajax loaded content

For a project I am trying to create an ajax-powered treeview control. My ajax scripts are working fine on the back end, but the tree is not being displayed properly. When I hard code the ajax response into my tree container, it is displayed properly:
However, when I try to load the tree via ajax I get this:
Here is my JS code:
$(document).ready(function() {
function customMenu(node) {
var items = {
createItem : {
label : "Generate random number(s)",
action: function() {
console.log("Creating children...");
var selectedId = $("#treeview").jstree("get_selected").attr("id");
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "libs/add.php",
data: "fact_id=" + selectedId,
dataType: "json",
success: function(data) {
console.log(data);
}
});
}
}
}
return items;
}
$("#treeview").jstree({
"plugins" : ["themes", "html_data", "ui", "crrm", "contextmenu"], contextmenu: {items: customMenu, select_node: true}
});
$.ajax({
url: "libs/display.php",
dataType: "json"
}).success(function(data) {
$("#treeview ul").append(data);
});
});
Does anyone have any idea what my problem is? Any help would be appreciated.
EDIT
After looking closer, I realize that the exact problem is that the necessary classes are not being added to the child nodes when calling via ajax. Still, I'm not sure why.
ANOTHER EDIT
display.php now contains this response text:
[
{
"attr": {
"id": 1
},
"data": 649,
"state": "closed"
},
{
"attr": {
"id": 1
},
"data": 108,
"state": "closed"
},
{
"attr": {
"id": 1
},
"data": 86,
"state": "closed"
},
{
"attr": {
"id": 1
},
"data": 46,
"state": "closed"
}
]
Am I headed in the right direction?
Is your stylesheet being included, and have you set up correct URLs to the icons? It looks to me like that's why your data isn't being styled. However, looking at your code, a more likely reason that you aren't getting your styling is because you are just calling an arbitrary AJAX call outside the jsTree scope.
Take a look at the docs for the json_data plugin for jsTree. It's easy to use, provided you set up display.php correctly to only fetch the node that jsTree is requesting. It will make concurrent calls and get the nodes it needs, your script simply needs to serve them to it:
$("#treeview").jstree({
"plugins" : ["themes", "html_data", "ui", "crrm", "contextmenu"],
"contextmenu": {
items: customMenu,
select_node: true
},
"json_data": {
"ajax": {
"url": "libs/display.php",
"data": function(n) {
return { id : n.attr ? n.attr("id") : 0
}
}
}
});
The json_data plugin basically acts as a wrapper for a jQuery AJAX call, but the events are bound directly the jsTree core and the returned results are handled by jsTree. You'll probably need to tweak your return values a bit depending on what display.php is responding with, and what you have set your tree up to look like structurally.
Edit
This is a similar post that might help you:
jsTree and AJAX > Load all data via ajax

Categories