Jstree: Loading json data asynchronously - javascript

I am currently trying to set up a Jstree, loading the data asynchronously from a webserver with the data provided in the json format. Before, I had the data stored in the html page itself, eg. by creating the <ul> </ul> structure. This worked well.
Then, following
http://agiliq.com/blog/2011/10/how-use-jstree/
I saved the data in the page as a Json string, which also worked fine. After that, I tried the asynchronous loading, where I encounter two problems:
When using Jstree jsTree 1.0-rc3 (as found in https://github.com/akshar-raaj/Using-jsTree), the tree structure is being built up correctly, but two expansion symbols appear left of each folder, which looks rather strange.
Then I tried to use the current version of Jstree, but this produces no tree at all and neither gives an error message.
Here is my html page:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<title>Menu test</title>
<link rel="stylesheet" href="/static/jsTree/themes/default/style.min.css" />
<script src="/static/jquery-1.11.1.js"></script>
<!--<script src="/static/jsTree/jstree.js"></script>-->
<script src="/static/jsTree/jstree_v3.js"></script> <!-- Current Version -->
<script>
$(function() {
$.ajax({
async : true,
type : "GET",
url : "../test2.json",
dataType : "json",
success : function(json) {
createJSTrees(json);
},
error : function(xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});
});
function createJSTrees(jsonData) {
$("#menuTree").jstree({
"json_data" : {
"data" : jsonData
},
"plugins" : [ "themes", "json_data", "ui" ]
});
}
</script>
</head>
<body>
Tree:
<div id="menuTree" >
</div>
</body>
</html>
And this is what test2.json gives out:
[ { "data" : "a", "children" :[ {"data":"b", "metadata":{"href":"b"}}, {"data":"c", "metadata":{"href":"c"}} ] } ]
Could you help me?
Thank you very much in advance!

Related

How to save a csv file uploaded from my machine into a data object in javascript?

I'm building a page that can display a chart of sensor data from a csv file. The user should be able to click on a button to choose a desired csv file from his machine to be displayed on a chart. I'm using the Highcharts library for that. The chart works as desired, but I can only input the csv file in code. When I upload a file and update nothing happens. So how can I make "data.csv" dynamic? My idea was to somehow save it into a global data object, that can then be passed into ajax url. I don't know how to implement this, since this is my very first javascript project.
<!DOCTYPE html> <!-- Write your comments here -->
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://code.highcharts.com/highcharts.js"></script> <!-- library include-->
<script src="https://code.highcharts.com/modules/data.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/highcharts-more.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.2/papaparse.js"></script>
<title>Airmeter</title>
</head>
<body>
<div id="container"></div>
<form id='form'>
<input type="file" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" id="input" />
<button type='submit'>
update the chart
</button>
</form>
<script>
$.ajax({
type: "GET",
url: "data.csv",
success: function (data) {
setTitle(data)
}
});
function setTitle(raw_data){
let newTitle;
let chart = Highcharts.chart('container', {
chart: {
zoomType: 'xy',
events: {
load: function() {
this.update({
title: {
text: 'Airmeter: '+ newTitle
}
})
}
}
},
xAxis:{
title:{
text: 'Zeit'
}
},
yAxis:{
title:{
text: 'CO2 in ppm'
}
} ,
exporting:{
enabled: true
},
title: {
text: null
},
credits:{
enabled: false
},
data: {
csv: raw_data,
parsed(e) {
newTitle=e[0][1] //set the first column as title of the chart
e.shift()
}
}
});
}
</script>
</body>
</html>
I would really appreciate help. Thanks for your time and have nice day!
If the CSV will always be on your local machine rather than a server, you don't really need to be using an AJAX call and you could use the FileAPI and a CSV parser to pass the data to your setTitle function.
But to help with your approach, try doing these changes to your code:
Add an onChange event to your input, so whenever a file is selected, the javascript code can 'react' to it.
Wrap your AJAX call in the 'change' event handler.
Pass the selected file name to your AJAX request's URL.
In terms of code changes (untested):
<script>
// Add an event listener, so when a file is selected, the graph is drawn again
document.getElementById("input").addEventListener("change", drawGraph, false);
// Wrap your current AJAX call in the event handler
function drawGraph() {
// Obtain the name of the file selected by the user in the <input>
var fileName = document.getElementById('input').files[0].name;
$.ajax({
type: "GET",
url: fileName, // use this name to fetch the selected file
success: function (data) {
setTitle(data)
}
});
}
// Leave the rest of the script block as it is
// ...
</script>

PapaParse doesn't handle my date correctly

I am having an issue creating a chart with some JSON that papaparse gives me. It continually gives me this error.
c3.js:2100 Failed to parse x '10-18-2018' to Date object
I've attempted to change the date format in csv to no avail. I have followed examples from c3 website, papaparse examples, and some stack overflow questions. Hopefully someone can tell me what I'm doing wrong so I can move forward with my project. Here is the code and the csv lines
app.js
"use strict";
$(function () {
$.get("108jbdata.csv") // Use HTTP GET (via Live-server) to retreive data from the static CSV file that we have included with our web assets.
.then(function (response) {
// Callback is executed when data is asynchronously received.
var parseOptions = {
// Parse options given to PapaParse.
header: true, // Allow PapaParse to derive field names from the CSV header line.
dynamicTyping: true, // Tell PapaParse to parse CSV string fields to the correct types for us.
};
var parsed = Papa.parse(response, parseOptions); // Parse the CSV data retreived from Live-server.
console.log(parsed);
var chart = c3.generate({
// Generate our chart.
bindto: "#chart",
data: {
json: parsed.data, // Plug the parsed CSV data into the chart.
keys: {
x: "Date",
xFormat: "%m-%d-%Y",
value: [
"KFISH", // Specify which column from the CSV file that we want to appear in the chart.
"WATER",
],
},
},
axis: {
x: {
type: "timeseries",
tick: {
format: "%m-%d-%Y",
},
},
},
});
})
.catch(function (err) {
// Handle any error that might have occurred.
console.error(err);
});
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>C3 chart template</title>
<link href="bower_components/c3/c3.css" rel="stylesheet" />
</head>
<body>
<div id="chart"></div>
<script src="bower_components/jquery/dist/jquery.js"></script>
<script src="bower_components/d3/d3.js"></script>
<script src="bower_components/c3/c3.js"></script>
<script src="bower_components/papaparse/papaparse.js"></script>
<script src="app.js"></script>
</body>
</html>
csv
Date,Iron,Chromium,Lead,Copper,Tin,Aluminum,Nickel,Silver,Silicon,boron,Sodium,Magnesium,Calcium,Barium,Phosphorous,Zinc,Molybdenum,Tin1,Vandium,W,Potassium,Antimony,Lithium,Maganese,Cadmium,VISC40,TAN,KFISH,WATER,PC0,PC1,pc2,pc3,pc4,pc5,PCISO0,PCISO1,PCISO2
"10-18-2018",0,0,3,0,0,0,0,0,2,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,65.03,0.37,15,0.0015,374,229,52,19,2,0,16,15,13
"11-2-2018",0,0,0,0,3,0,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,8,0,0,0,64.63,0.5,24,0.0024,2915,388,15,3,0,0,19,16,11
"11-29-2018",0,0,0,0,0,0,0,0,2,0,0,0,1,0,0,1,1,0,0,0,0,0,0,0,0,64.13,0.93,23,0.0023,3292,527,16,4,1,0,19,16,11
"12-13-2018",0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,63.95,0.91,20,0.002,3076,517,14,5,1,1,19,16,11
"1-14-2019",0,0,0,0,0,0,1,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64.74,0.84,13,0.0013,4007,698,32,9,1,0,19,17,12
I got past being unable to parse the string date from the csv as a Date by going through each element and parsing it as a Date before I sent it off to the generate function.
parsed.data.forEach((h) => {
h.Date = Date.parse(h.Date);
});

Rendering local templates using Handlebars.js

I've just started using handlebars.js in attempt to move away from rendering dynamic data the ugly way using string concat and injection. I am trying to separate the template script from the main HTML file and render the template file via a function call. Here is what I've got:
script.js
----------
$(function() {
var myData = { requests: [
{id: "1", firstname: "Roger", lastname: "Jones", age: 24},
{id: "2", firstname: "Phillip", lastname: "Green", age: 44}
]};
$.ajax({
url: 'templates/requests.html',
dataType: 'html',
cache: false,
success: function(data, status, response) {
var template = Handlebars.compile(response.responseText);
var context = myData;
$('#InjectTemplate_Requests').html(template(context));
}
});
});
index.html
-------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Handlebars</title>
</head>
<body>
<div id="InjectTemplate_Requests">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0-alpha.4/handlebars.min.js"></script>
<script src="script.js"></script>
</body>
</html>
requests.html (template file inside the 'templates' directory)
--------------
<table>
<thead>
<th>Name</th>
<th>Status</th>
<th>Type</th>
</thead>
<tbody>
{{#requests}}
<tr>
<td>{{firstname}} {{lastname}}</td>
<td>{{age}}</td>
</tr>
{{/requests}}
</tbody>
</table>
File Structure
--------------
index.html
|
script.js
|
|
|---templates
|
|
|---requests.html
I seem to be getting this error on the console: Failed to load resource: The requested URL was not found on this server. However, when I add the template to Index.html (and remove ajax call from the script file), the template renders just fine.
Can anybody shed some light as to why this is happening and how I can fix this?
Thanks in advance.
I managed to fix the issue by changing this:
<script src="http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0-alpha.4/handlebars.min.js"></script>
to this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script>
Thanks for all the suggestions though.
This isn't an issue with Handlebars; it's an issue with your URL (as the error notes); I noticed you're using a relative path
templates/requests.html
in the AJAX request. If you use an absolute URL instead (/templates/requests.html), does that fix the problem?
Likewise, is whatever backend server you're using configured to serve that directory?

How to load and print json array/object in javascript

I do not have any json and d3 knowledge (just started to read few hours back) but have very basic javascript knowledge. I have to load a json file and print all the array and objects on the console using d3. I was wondering if anyone can help me to solve it. Actually, I did it but does not work :(
My json file.
{
"addressfile": "info",
"struct": {
"address": [
[
"A",
"B",
],
[
"B",
"C",
],
],
"address1": {
"address2": {
"address3": {
"zip": [
"NUMBER",
0
]
},
"address_type": "Home"
},
}
},
"COUNTRY": {},
}
My javascript code...
<!DOCTYPE html>
<meta charset="utf-8">
<style>
<body>
<script>
//LOADING JSON FILE
d3.json("address.json", function(error, root) {
if (error) return console.error(error);
for (var p in location) if (location.hasOwnProperty(p)) {
console.log(p + " : " + location[p]);
}
}
</script>
</body>
</html>
Please help me to solve it...
Try
d3.json("appinfo.json", function(location) {
I know the docs say the callback takes two parameters, in a project I recently did with d3 version 3.4.13, the callback function would only work if I only passed it the data parameter.
your code missing a closing parenthesis - );
correct code would be :
<script>
d3.json("appinfo.json", function(error, root) {
if (error) return console.error(error);
console.log(root) // output -your JSON data as pojo
//for (var p in location) if (location.hasOwnProperty(p)) {
// console.log(p + " : " + location[p]);
//}
});
</script>
make sure you write correct url to your json file in first parameter to d3.json().
make sure that appinfo.json contain correct json object, you can test it at http://jsonlint.com/
Thanks everyone.. After struggling I got the solution..
Solution: External Json files are not supported by the browsers ..so I needed to use webserver. Then I was able to see the output of it in the console.
the final code:
<!DOCTYPE html>
<meta charset="utf-8">
<head>
<script src="http://d3js.org/d3.v3.min.js"></script>
</head>
<body>
<script>
d3.json("address.json", function(location) {
console.log(location)
});
</script>
</body>
</html>
Hope it might help others to solve in minutes not in hours like me.....

Configuring dojo datagrid to use remote server URL

I am unable to configure a dojo data grid to remote server. The tutorial example I am following is:
http://dojotoolkit.org/documentation/tutorials/1.6/populating_datagrid/demo/datagrid-items.html
My code is written in a single jsp and is shown here:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Demo: dojox.grid.DataGrid Simple Structure</title>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/resources/dojo.css">
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dijit/themes/claro/claro.css">
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojox/grid/resources/Grid.css">
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojox/grid/resources/claroGrid.css">
<!-- load dojo and provide config via data attribute -->
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6.0/dojo/dojo.xd.js"
data-dojo-config="isDebug: true,parseOnLoad: true">
</script>
<script>
dojo.require("dojox.grid.DataGrid");
dojo.require("dojo.data.ItemFileWriteStore");
var grid, store;
dojo.ready(function(){
store = new dojo.data.ItemFileWriteStore({
url: "MilestoneAjaxPopulateMsListEditor.json"
});
grid = new dojox.grid.DataGrid({
query: { id: "*" },
store: store,
structure: [
{ name: "First Name", field: "first", width: "25%" },
{ name: "Last Name", field: "last", width: "25%" }
]
},dojo.byId("grid"));
grid.startup();
});
</script>
</head>
<body class="claro">
<%# include file="ui_init.jsp" %>
<h1>Demo: dojox.grid.DataGrid Simple Structure</h1>
<br/>
<div id="grid"></div>
<%# include file="footer.jsp" %>
</body>
</html>
The Ajax request completes without any error (getting 200 OK response code). I am getting the following JSON from the remote server and is shown in firebug:
{"msdetails":[
{"first":"146", "last":"Concept Commit"}
, {"first":"147", "last":"Execution Commit"}
, {"first":"148", "last":"EFT Start"}
, {"first":"149", "last":"Throttle Pull Review"}
, {"first":"150", "last":"Throttle Pull"}
, {"first":"151", "last":"PSIRT Verification"}
, {"first":"152", "last":"Commit Test"}
, {"first":"153", "last":"FTS Complete"}
, {"first":"154", "last":"Image List"}
, {"first":"155", "last":"Upgrade Planner"}
, {"first":"156", "last":"Market Matrix"}
, {"first":"157", "last":"Reg Test Cmp"}
, {"first":"158", "last":"ISSU CM Creation"}
, {"first":"144", "last":"Build Start Time"}
, {"first":"159", "last":"ISSU CM Verification"}
, {"first":"160", "last":"OPUS"}
, {"first":"161", "last":"Docs Complete"}
, {"first":"162", "last":"TAC Readiness"}
, {"first":"145", "last":"CCO FCS"}
, {"first":"163", "last":"Field CCO FCS"}
, {"first":"164", "last":"HPC Date"}
, {"first":"165", "last":"EoLA"}
, {"first":"166", "last":"EoS"}
, {"first":"167", "last":"EoL/EoSM"}
, {"first":"168", "last":"EoVS Date"}
, {"first":"169", "last":"End of Support"}
]}
The error I get is:
Please help with any pointers on this error.
For ItemWriteStore to work properly, your array part of the json should be given key name as "items" and also, your json objects need to have key "id", if not then, you also need to specify which key will act as id of json objects
{"identifier:"first","items":[
{"first":"146", "last":"Concept Commit"}
, {"first":"147", "last":"Execution Commit"}
, {"first":"148", "last":"EFT Start"}
, {"first":"149", "last":"Throttle Pull Review"}]}

Categories

Resources