How to generate a jstree using AJAX? - javascript

I have been having problems generating a JsTree using data from my server. I have tried different formats and appending an existing tree, no dice. The only thing that happens is that it the jstree div gets replaced by
<div id="jstree" class="jstree jstree-1 jstree-default jstree-leaf" role="tree" aria-multiselectable="true" tabindex="0" aria-activedescendant="j1_loading" aria-busy="false"><ul class="jstree-container-ul jstree-children" role="group"></ul></div>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jsTree test</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
</head>
<body>
<div id="jstree">
</div>
<script>
$(function() {
$.ajax({
async : true,
type : "GET",
url : "/treeTest2",
dataType : "json",
success : function(json) {
// alert(JSON.stringify((json)));
createJSTrees(json);
},
error : function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
function createJSTrees(jsonData) {
$("#jstree").jstree({
"json_data" : {
"data" : jsonData
},
"plugins" : [ "themes", "json_data", "ui" ]
}).bind("select_node.jstree", function (e, data) {
alert(e);
});
}
</script>
</body>
</html>
Heres what the alert(JSON.stringify((json))); returns
[
{
"a_attr": {
"id": 1
},
"text": "lvl1",
"icon": "snipplet",
"metadata": null,
"children": [
{
"a_attr": {
"id": 3
},
"text": "lvl2",
"icon": "snipplet",
"metadata": null,
"children": [
{
"a_attr": {
"id": 5
},
"text": "lvl3",
"icon": "snipplet",
"metadata": null,
"children": []
}
]
},
{
"a_attr": {
"id": 4
},
"text": "lvl2",
"icon": "snipplet",
"metadata": null,
"children": []
}
]
},
{
"a_attr": {
"id": 2
},
"text": "lvl1",
"icon": "snipplet",
"metadata": null,
"children": []
}
]
The metadata tag is needed for data that will be needed later. Everything will be otganised into folders and snipplets. And the id tag will be used in hyperlinks.

I believe id="jstree" conflicts with the global variable jstree.
Indeed, If you give an ID to an element, this element is directly available in JS, without doing anything :
myGreatDiv.innerHTML = "It works"
<div id="myGreatDiv"></div>
So, you include the JsTree library, which defines window.jstree.
Then, you create a div with id="jstree", which automatically overwrites window.jstree.
Solution (I guess) : call your div something else, like
<div id="jstree_div">

Here's the solution.
function createJSTrees(jsonData) {
$("#kautkas").jstree({
'core' : {
'data' : jsonData
}
});
}

Related

Node.js parse non-standard hast data to HTML?

How can we convert non-standard hast (which is parsed from a Markdown file) to HTML?
For example, this is the HTML tree data I have:
{
"_path": "/hello",
"_draft": false,
"_partial": false,
"_empty": false,
"title": "Hello!",
"description": "",
"body": {
"type": "root",
"children": [
{
"type": "element",
"tag": "h1",
"props": {
"id": "hello!"
},
"children": [
{
"type": "text",
"value": "Hello!"
}
]
}
],
"toc": {
"title": "",
"searchDepth": 2,
"depth": 2,
"links": []
}
},
"_type": "markdown",
"_id": "content:hello.md",
"_source": "content",
"_file": "hello.md",
"_extension": "md"
}
How can I parse that 'body' bit to HTML in Node.js?
I tried to use hast-util-to-html:
import { toHtml } from 'hast-util-to-html'
console.log('data.body =', toHtml(data.body))
But I got the following error:
TypeError: Cannot read properties of undefined (reading 'toLowerCase')
I think the tag key in the data should be tagName for using hast-util-to-html. tag and prop are non-standard keys I suppose, how can I standardise them?

AngularJS rendering from deeply nested jsonp

I am new to JSON and also AngularJS. I'm trying to access data elements in a deeply nested remote json file. I can manage to render the whole JSON results in my view. However, I can't seem to target the elements that are in an array deep inside the JSON. It's from Yahoo Currency.
This is my controller and view that renders the entire JSON file:
controller
var app = angular.module('app', []);
app.controller('DataCtrl', function ($scope, $http) {
$http.jsonp('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22http%3A%2F%2Ffinance.yahoo.com%2Fwebservice%2Fv1%2Fsymbols%2Fallcurrencies%2Fquote%3Fformat%3Djson%22&format=jsonp&callback=JSON_CALLBACK').success(function (data) {
$scope.data = data;
});
});
view
<!doctype html>
<html ng-app="app" >
<head>
<meta charset="utf-8">
<title>LIVE</title>
<!-- <link rel="stylesheet" href="style.css"> -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="DataCtrl">
<h1>Live from JSON feed</h1>
<ul>
<li ng-repeat="row in data">
{{ data }}
</li>
</ul>
</body>
</html>
I tried writing the controller like this:
var app = angular.module('app', []);
app.controller('DataCtrl', function ($scope, $http) {
$http.jsonp('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22http%3A%2F%2Ffinance.yahoo.com%2Fwebservice%2Fv1%2Fsymbols%2Fallcurrencies%2Fquote%3Fformat%3Djson%22&format=jsonp&callback=JSON_CALLBACK').success(function (data) {
var pair = { name };
// $scope.data = data;
if(data) {
if (data.results) {
pair.name = data.results.list.resources[0].resource.fields.name;
}
}
});
});
But that doesn't work. Here is the JSON (partial) .. I'm trying to access the "name", "price", and "utctimestamp" fields for each resource:
{
"query": {
"count": 1,
"created": "2015-11-07T05:42:03Z",
"lang": "en-US",
"diagnostics": {
"publiclyCallable": "true",
"url": {
"execution-start-time": "0",
"execution-stop-time": "23",
"execution-time": "23",
"content": "http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json"
},
"user-time": "25",
"service-time": "23",
"build-version": "0.2.311"
},
"results": {
"list": {
"meta": {
"type": "resource-list",
"start": "0",
"count": "173"
},
"resources": [
{
"resource": {
"classname": "Quote",
"fields": {
"name": "USD/KRW",
"price": "1152.994995",
"symbol": "KRW=X",
"ts": "1446874620",
"type": "currency",
"utctime": "2015-11-07T05:37:00+0000",
"volume": "0"
}
}
},
{
"resource": {
"classname": "Quote",
"fields": {
"name": "SILVER 1 OZ 999 NY",
"price": "0.068046",
"symbol": "XAG=X",
"ts": "1446850711",
"type": "currency",
"utctime": "2015-11-06T22:58:31+0000",
"volume": "100"
}
}
},
{
"resource": {
"classname": "Quote",
"fields": {
"name": "USD/VND",
"price": "22364.000000",
"symbol": "VND=X",
"ts": "1446874620",
"type": "currency",
"utctime": "2015-11-07T05:37:00+0000",
"volume": "0"
}
}
},
...
For what it's worth, jsonp seems to return some kind of xml-looking stuff when I append the callback=JSON_CALLBACK to the url, like this:
JSON_CALLBACK({"query":{"count":"1","created":"2015-11-07T16:08:29Z","lang":"en-US"},"results":["<list><meta><type>resource-list</type><start>0</start><count>173</count></meta><resources><resource><classname>Quote</classname><fields><name>USD/KRW</name><price>1152.994995</price><symbol>KRW=X</symbol><ts>1446900900</ts><type>currency</type><utctime>2015-11-07T12:55:00+0000</utctime><volume>0</volume></fields></resource></resources><resources><resource><classname>Quote</classname><fields><name>SILVER 1 OZ 999 NY</name><price>0.068046</price><symbol>XAG=X</symbol><ts>1446850711</ts><type>currency</type><utctime>2015-11-06T22:58:31+0000</utctime><volume>100</volume></fields></resource></resources><resources><resource>
...
Is there a problem with how I'm using JSONp? I'm getting the data set rendered to my view (above) but it's all in the funky xml syntax. How to go about grabbing the 3 values I need from that to an array and rendering in a <ul>??
You can use your original controller, you only had problems in the view. It would work if you substitute it by this one:
<!doctype html>
<html ng-app="app" >
<head>
<meta charset="utf-8">
<title>LIVE</title>
<!-- <link rel="stylesheet" href="style.css"> -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="DataCtrl">
<h1>Live from JSON feed</h1>
<ul>
<li ng-repeat="res in data.query.results.list.resources">
{{ res.resource.fields.name }}: {{ res.resource.fields.price }}, {{ res.resource.fields.utctime }}
</li>
</ul>
</body>
</html>
Here is the Plunker using your JSON example: http://plnkr.co/edit/wzF5t9dTZt49n5eq9N1L?p=preview

jQuery how to implement nested $.each() in DataTables

I get Json data from server in order to display information by using DataTables.
In this json, there are rows, where in a column there may exist more than one value, so it's a multidimensional array as follows (I show just an excerpt of the array):
{
"info_table": [
{
"date": "2015-01-06",
"subject": "Some subject or title",
"type": "article",
"url": null,
"pdf": null,
"notes": null,
"created_at": "2015-06-26 13:38:53",
"updated_at": "2015-06-26 13:38:53",
"institute": "Some Institute name",
"researchers": [
{
"name": "CARL SMITH"
}
],
"assistants": [
{
"name": "YULIA SMIRNOVA"
}
]
}
]
}
The DataTable works fine so far:
$('#notes_table table').append('<thead><tr><th>Researchers</th><th>Date</th></tr></thead><tbody></tbody>');
$.each(response.info_table,function(i,item){
$('#notes_table').find('tbody').append('<tr><td>'+item.researchers+'</td><td>'+item.date+'</td></tr>');
});
The date column values are displayed fine, however, for the researcherscolumn only [object Object] is displayed. If I try to use a nested $.each() as follows:
$('#notes_table table').append('<thead><tr><th>Researchers</th><th>Date</th></tr></thead><tbody></tbody>');
$.each(response.info_table,function(i,item){
$.each(item.researchers, function(j,item2){
$('#notes_table').find('tbody').append('<td>'+item2.name+'</td>');
});
$('#notes_table').find('tbody').append('<td>'+item.date+'</td>');
});
I don't get anything, I just see a DataTables message saying Sorry, no results found.
What am I missing? Any ideas?
Solution
Thanks to BLSully:
The working code looks as follows:
var table = $('#table_id').DataTable({
columns: [{
data: 'researchers[, ].name',
title: 'Researchers'
}, {
data: 'date',
title: 'Date'
}]
});
table.rows.add(data).draw();
And that was it.
I'm assuming based on your wording, you're using datatables. Given that, I'm going to provide an alternate example of handling databinding to your table that utilizes the design of the plugin rather than manual DOM manipulation. So.. this isn't exactly an answer to the question, but rather a suggestion of the proper way of doing what you're trying to achieve (given the context you've provided. Depending on how your retrieving your data, there may be some slight changes)
The correct way to add orthogonal json data to your table is by creating column definitions so the table knows which columns to display your data, along with rules around how it's to be displayed.
I set up an example based on your data (expanded a bit to explain how to deal with deeply nested objects and arrays). The really relevant bit is the data property on the first column: researchers[, ].name. The syntax of that value instructs datatables to treat the property researchers as an array, and displaying it in a comma-separated fashion. Because the array elements are JavaScript objects, the .name following the square brackets instructs DataTables on which property of the object should be displayed.
http://live.datatables.net/domivewi/1/
var data = [
{
"date": "2015-01-06",
"subject": "Some subject or title",
"type": "article",
"url": null,
"pdf": null,
"notes": null,
"created_at": "2015-06-26 13:38:53",
"updated_at": "2015-06-26 13:38:53",
"institute": "Some Institute name",
"researchers": [{
"name": "CARL SMITH"
},{
"name": "JOHN DOE"
}],
"assistants": [
{
"name": "YULIA SMIRNOVA"
}
]
},{
"date": "2015-01-06",
"subject": "Some subject or title",
"type": "article",
"url": null,
"pdf": null,
"notes": null,
"created_at": "2015-06-26 13:38:53",
"updated_at": "2015-06-26 13:38:53",
"institute": "Some Institute name",
"researchers": [{
"name": "FRED FLINSTONE"
},{
"name": "WILMA FLINTSTONE"
}],
"assistants": [
{
"name": "BARNEY RUBBLE"
}
]
}
];
var table = $('#demo').DataTable({
columns: [{
//this is the important bit here. See explanation above
data: 'researchers[, ].name',
title: 'Researchers'
}, {
data: 'date',
title: 'Date'
}]
});
//this line adds new rows to the table and redraws
table.rows.add(data).draw();
body {
font: 90%/1.45em "Helvetica Neue", HelveticaNeue, Verdana, Arial, Helvetica, sans-serif;
margin: 0;
padding: 0;
color: #333;
background-color: #fff;
}
div.container {
min-width: 980px;
margin: 0 auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<link href="//datatables.net/download/build/nightly/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<script src="//datatables.net/download/build/nightly/jquery.dataTables.js"></script>
<meta charset=utf-8 />
<title>DataTables - JS Bin</title>
</head>
<body>
<table id="demo"></table>
</body>
</html>
Try This ...
First of all save the json string in javascript array.
Like this ...
var myArray = Array();
myArray = {
"info_table": [
{
"date": "2015-01-06",
"subject": "Some subject or title",
"type": "article",
"url": null,
"pdf": null,
"notes": null,
"created_at": "2015-06-26 13:38:53",
"updated_at": "2015-06-26 13:38:53",
"institute": "Some Institute name",
"researchers": [
{
"name": "CARL SMITH"
}
],
"assistants": [
{
"name": "YULIA SMIRNOVA"
}
]
}
]
}
// Then Execute like this ..
$('#notes_table table').append('<thead><tr><th>Researchers</th><th>Date</th></tr></thead><tbody></tbody>');
$.each(myArray.info_table,function(i,item){
for( var i; i < item.researchers.length, i++){
$('#notes_table').find('tbody').append('<td>'+item.researchers[i].name+'</td>');
});
$('#notes_table').find('tbody').append('<td>'+item.date+'</td>');
});

Load JSON Data Using jQuery AJAX

I need to print this information when clicking a button and sorting if by date, so far i have this: I have json file that looks like this, but I haven't been able to print it on the page and still haven't got to the sorting by date part. I am not sure if the problem is the link to the ajax version i am using or what is the problem, because i saw an example that looks just like this on youtube and it works just fine.
JSON:
  [
{
"users": [
{
"name": "user1",
"Endorsement": "some comment",
"date": "8/11/2012"
},
{
"name": "user2",
"Endorsement": "some comment2",
"date": "9/27/11"
},
{
"name": "user3",
"Endorsement": "some comment3"
},
{
"name": "user4",
"Endorsement": "some comment4",
"date": "4/2/13"
},
{
"name": "user5",
"Endorsement": "some comment5"
},
{
"name": "user6",
"Endorsement": "some comment6",
"date": "3/17/13"
},
{
"name": "user7",
"Endorsement": "some comment7",
"date": "5/22/13"
},
{
"name": "user8",
"Endorsement": "some comment8",
"date": "9/27/13"
}
]
}
]
HTML updated:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contact</title>
<link rel="shortcut icon" href="stridesFavicon.ico">
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/bootstrap-responsive.css">
<link rel="shortcut icon" href='http://sites.google.com/site/lowcoupling/favicon_16x16.ico' />
</head>
<body>
<!--Body content-->
<div id='Div1'>
Get JSON Data
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
<script src="myscript.js" type="text/javascript" /></script>
<script type="text/javascript">
$(document).ready(function () {
$('.dropdown-toggle').dropdown();
});
</script>
</body>
</html>
JS updated:
$("#clickme").click(function () {
$.getJSON("users.json", function (data) {
var items = [];
$.each(data, function (key, dvalue) {
$.each(dvalue, function (key, value) {
items.push('<li id="' + key + '">' + value + '</li>');
});
});
$('<ul/>', {
'class': 'interest-list',
html: items.join('')
}).appendTo('body');
});
});
But is not working. meaning is not loading user names; instead it is printing something like this every time i click the link:
•[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
the jason is missing some commas, every line inside the json should end with a comma unless it is the last child in the scope, which makes it:
[
{
"users": [
{
"name": "user1",
"Endorsement": "some comment",
"date": "8/11/2012"
},
{
"name": "user2",
"Endorsement": "some comment2",
"date": "9/27/11"
},
{
"name": "user3",
"Endorsement": "some comment3"
},
{
"name": "user4",
"Endorsement": "some comment4",
"date": "4/2/13"
},
{
"name": "user5",
"Endorsement": "some comment5"
},
{
"name": "user6",
"Endorsement": "some comment6",
"date": "3/17/13"
},
{
"name": "user7",
"Endorsement": "some comment7",
"date": "5/22/13"
},
{
"name": "user8",
"Endorsement": "some comment8",
"date": "9/27/3"
}
]
}
]
try !
$("button").click(function () {
$.getJSON("users.json", function (obj) {
$.each(obj.users, function (key, value) {
$("ul").append("<li>" + value.name + "</li>");
});
});
});
and if there is error then use debug console in browser.
and either make a fiddle or write what is error. and there seems no ul element in your html.
The json is not valid. I validated using http://jsonlint.com/ and it says error at line 6. You left a comma in below part:
"Endorsement": "some comment"
"date":"8/11/2012"
This is the first endorsement-date pair
$("button").click(function () {
$.getJSON("users.json", function (data) {
for (i in data)
{
for (k in data[i]) {
alert(data[i][k]);
}
});
});
$.ajax({
type:'POST',
url:'Default.aspx/GetPro',
data:"{Pid:'"+ faram+"'}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
cache: false,
success: function(msg) {
alert("{Pid:'"+ faram+"'}");
var orders =msg;
if (orders.length > 0) {
test(orders);
}
else {
alert("No Record Found");
}
},
error: function(xhr, textStatus, errorThrown) {
alert(xhr.status);
alert(errorThrown);
alert(xhr.responseText);
}
});
function test(data)
{
for (i in data)
{
//ProductName Is Property Field Of c# Object
alert(data[i]['ProductName'])
}
}

parse facebook json javascript

I am using javascript api to get facebook comments.
i am getting the following json result , but how can i parse them to use on my page ?
{
"id": "1234567891_2823098717038_3160191",
"from": {
"name": "User",
"id": "1234567891"
},
"message": "comment only...",
"can_remove": true,
"created_time": "2012-05-05T07:43:11+0000"
},
{
"id": "1234567891_2823098717038_3160281",
"from": {
"name": "User",
"id": "1234567891"
},
"message": "just another comment...",
"can_remove": true,
"created_time": "2012-05-05T08:14:17+0000"
},
{
"id": "1234567891_2823098717038_3160336",
"from": {
"name": "user2",
"id": "56265654845454"
},
"message": "congratz dear :)",
"can_remove": true,
"created_time": "2012-05-05T08:29:05+0000"
}
],
"paging": {
"next": "http://link.dddd"
}
}
How can i loop through this and display the contents ?
jQuery solution is acceptable.
Thank you.
Use JQuery.parseJSON: http://api.jquery.com/jQuery.parseJSON/
assoc_data = jQuery.param(response); //where response is your json
$.ajax({
type: "POST",
url: "submit_fb_data.php",
data: assoc_data,
success: function(data) {
//etc
}
});
make sure you use a >=1.4 jquery version

Categories