I would like to load data from a JSON file on my computer. I know that I can't read without HTTP server so I would like to creat an input field. My file is succeffuly read but when I send the data to function to create the Bubble Chart, nothing is created. If I load from local it works (I execute a HTTP server). This is the code :
<script type="text/javascript">
var json;
function handleFileSelect(evt) {
var files = evt.target.files;
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
function handleFileSelect(evt) {
var files = evt.target.files;
var output = [];
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
reader.onload = (function (theFile) {
return function (e) {
json = JSON.parse(e.target.result);
alert('json global var has been set to parsed json of this file here it is unevaled = \n' + JSON.stringify(json));
initData(JSON.stringify(json)); // Doesn't works
//initData("data.json"); // Works
}
})(f);
reader.readAsText(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
function initData(data){
d3.json(data, function(error, root) {
if (error) throw error;
var node = svg.selectAll(".node")
.data(bubble.nodes(classes(root))
// .....
This is an online example for Plunker : https://plnkr.co/edit/T8WFvj0qtMW5mFK6gOjO?p=preview
Thanks.
Thanks for your answers ! This is the good code, just send the JSON and dont use d3.json
<script type="text/javascript">
var json;
function handleFileSelect(evt) {
var files = evt.target.files;
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
function handleFileSelect(evt) {
var files = evt.target.files;
var output = [];
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
reader.onload = (function (theFile) {
return function (e) {
json = JSON.parse(e.target.result);
alert('json global var has been set to parsed json of this file here it is unevaled = \n' + JSON.stringify(json));
initData(json); // Doesn't works
//initData("data.json"); // Works
}
})(f);
reader.readAsText(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
function initData(root){
var node = svg.selectAll(".node")
.data(bubble.nodes(classes(root))
//....