I only write questions when I'm truly desperate, I hope someone can point me in the right direction.
- I am trying to build a pie chart using the data from a django model that would appear in a user page, so each user is getting different data returned in their http get query.
- I am currently in development, so I'm still fetching from localhost.
- I believe my Django is well because js ajax works well, as it should. Maybe the problem is the production environment (fetching from localhost?)
// javascript
var original_data = [{
"coin": "BTC",
"stake": 5
},
{
"coin": "LTC",
"stake": 6
},
{
"coin": "DASH",
"stake": 9
}
];
var data = [];
var url = "http://localhost:8000/wallet/data";
d3.json(url, (datos) => {
loadGraph(datos)
});
function loadGraph(data) {
console.log("NEW DATA: ");
console.log(data);
var svgWidth = 500,
svgHeight = 300,
radius = Math.min(svgWidth, svgHeight) / 2;
var svg = d3.select('svg')
.attr("width", svgWidth)
.attr("height", svgHeight);
//Create group element to hold pie chart
var g = svg.append("g")
.attr("transform", "translate(" + svgWidth / 2 + "," + radius + ")");
var color = d3.scaleOrdinal(d3.schemeCategory10);
var pie = d3.pie().value(function(d) {
return d.stake;
});
var path = d3.arc()
.outerRadius(radius)
.innerRadius(radius / 2);
var arc = g.selectAll("arc")
.data(pie(data))
.enter()
.append("g");
arc.append("path")
.attr("d", path)
.attr("fill", function(d) {
return color(d.data.stake);
});
var label = d3.arc()
.outerRadius(radius)
.innerRadius(0);
arc.append("text")
.attr("transform", function(d) {
return "translate(" + label.centroid(d) + ")";
})
.attr("text-anchor", "middle")
.text(function(d) {
return d.data.coin + ":" + d.data.stake + "%";
});
}
// TRYING WITH D3js json method:
d3.json(url).then((data) => {
console.log(data);
console.log(url);
});
// ** Data returns empty array!
// ** Maybe need to do something first?
// TRYING WITH js ajax method:
// var xhttp = new XMLHttpRequest();
// xhttp.onreadystatechange = function() {
// if (this.readyState == 4 && this.status == 200) {
// var data = this.responseText;
// console.log(this.responseText);
// loadGraph(data);
// }
// };
// xhttp.open("GET", url, true);
// xhttp.send();
// ** Data loads fine, but d3 will not paint chart.
// ** Instead, undefined is printed where the graph should be.
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.5.0/d3.js"></script>
As shown in the code, I have loaded sample data to make sure the pie chart is well defined. It works with sample data, but maybe there's something that needs to change for it to work from an external resource.
The examples I have seen in the web for external data sources normally point to a .json file stored somewhere. That makes no sense as this works like an API. Maybe the problem lies here, but I don't know how to continue.
Any help is welcome. I am truly going mad. Cheers.