I'm Trying to Display JSON Data in Chart.js But I Can't Find a way to use the actual_JSON Variable (which is my JSON file as object) in chart, because it's local. can someone help me in this?
//Get JSON Data
function loadJSON(callback) {
var xhr = new XMLHttpRequest();
xhr.overrideMimeType("application/json");
xhr.open('GET', 'https://filebin.net/bddbcas2xtfiufnj/data.json?t=at5f150y', true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == "200") {
callback(xhr.responseText);
}
};
xhr.send(null);
}
(function init() {
loadJSON(function(response) {
// Parse JSON string into object
var actual_JSON = JSON.parse(response);
consumeData(actual_JSON); //Use this to consume JSON Data
});
})()
//*********************************************************************
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: [], //Using JSON Object Here
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45]
}]
},
// Configuration options go here
options: {}
});
<!DOCTYPE html>
<html>
<body>
<canvas id="myChart"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
</body>
</html>
You can use jQuery.getJSON(): function including JQuery library in your software
$.getJSON('https://filebin.net/bddbcas2xtfiufnj/data.json?t=at5f150y', function(data) {
//data is the JSON string. Pass data to chart
});
Related
I am trying to draw a two-line chart with two datasets that share the same labels using chart.js on my ASP.NET MVC app.
I am only getting the data from "Value" plotted on the chart and not "Age" and I cannot find the reason why.
Relevant Controller code:
public ActionResult GetLineChartData()
{
List <LineChartData> dataForLineChart = new List <LineChartData> ();
dataForLineChart.Add(new LineChartData {
Date = DateTime.NOW, Value = 100, Age = 20
});
return Json(dataForLineChart, JsonRequestBehavior.AllowGet);
}
Relevant View code:
$.ajax({
type: "Post",
url: '#Url.Action("GetLineChartData", "Posts")',
contentType: false,
processData: false,
data: dataFromForm,
dataType: "json",
traditional: true,
success: function (data) {
console.log(data);
var labels = data.map(function (e) {
return e.Date;
});
var data = data.map(function (e) {
return e.Value;
});
var data2 = data.map(function (e) {
return e.Age;
});
var ctx = scatterChart.getContext('2d');
var config = {
type: 'line',
data: {
labels: labels,
datasets: [{
label: "Test"
data: data,
backgroundColor: 'rgba(0, 119, 204, 0.3)'
},
{
label: "Test",
data: data2,
backgroundColor: 'rgba(242, 204, 143, 1)'
}
]
}
};
}
});
(Some code I do not consider important is hidden)
Issue & Concern
Because the below line overwrites the original data value.
var data = data.map(function (e) {
return e.Value;
});
After the above line, now the data array was overwritten as an array of integers instead of an array of objects. Based on your sample response from API, the current value of data will be: [100].
var data2 = data.map(function (e) {
return e.Age;
});
From the above line, it can't find the Age property in the element. Hence the result of data2 will be: [undefined].
This is why the data2 is not rendered in the chart.
Solution
Create another variable for the data transformation to avoid overwriting the existing data value.
var dataset = data.map(function (e) {
return e.Value;
});
var dataset2 = data.map(function (e) {
return e.Age;
});
var config = {
type: 'line',
data: {
labels: labels,
datasets: [
{
label: 'Test',
data: dataset,
backgroundColor: 'rgba(0, 119, 204, 0.3)',
},
{
label: 'Test',
data: dataset2,
backgroundColor: 'rgba(242, 204, 143, 1)',
},
],
},
};
Demo # StackBlitz
I have managed to get a count of items in list by status, but cant seem to figure out how to add the data into Chart.js. I have tried referencing my dataset from within the chart but that does not seem to work. Any assistance would be greatly appreciated. I have pieced together some code to try to get this to work but cant seem to get this last piece. ps. This code is being used in content editor in SharePoint.
Thank you,
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<button onclick="GetListItems();" type="button">Get All List Items</button>
<div>
<canvas id="myChart"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
function GetListItems() {
var url = "https://contoso.sharepoint.com/sites/Mysite/_api/web/lists/getByTitle('Mylist')/items?$top=500";
$.ajax({
url: url,
type: "GET",
headers: {
"accept": "application/json; odata=verbose"
},
success: onSuccess
});
}
function onSuccess(data) {
var items = data.d.results;
const MyDataset = [];
var NewItems = items.filter(function(ItemStatus) {
return ItemStatus.Status == "New";
});
var InProcItems = items.filter(function(ItemStatus) {
return ItemStatus.Status == "In Process";
});
var CompItems = items.filter(function(ItemStatus) {
return ItemStatus.Status == "Completed";
});
MyDataset.push(NewItems.length);
MyDataset.push(InProcItems.length);
MyDataset.push(CompItems.length);
console.log(MyDataset);
}
const labels = ['New', 'Completed', 'Inproccess'];
const data = {
labels: labels,
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [5, 5, 5, 2, 2, 30, 45],// use MyDataset here instead of random.
}]
};
const config = {
type: 'bar',
data: data,
options: {}
};
</script>
<script>
const myChart = new Chart(
document.getElementById('myChart'),
config
);
</script>
That should do what's you expect. I cannot test because data ajax call is not public.
<!-- External Lib -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<!-- HTML / Template -->
<button onclick="GetListItems();" type="button">Get All List Items</button>
<div>
<canvas id="myChart"></canvas>
</div>
<!-- Javascript -->
<script>
function GetListItems() {
var url = "https://contoso.sharepoint.com/sites/Mysite/_api/web/lists/getByTitle('Mylist')/items?$top=500";
$.ajax({
url: url,
type: "GET",
headers: {
"accept": "application/json; odata=verbose"
},
success: onSuccess
});
}
function onSuccess(data) {
var items = data.d.results;
var MyDataset = [];
var NewItems = items.filter(function(ItemStatus) {
return ItemStatus.Status == "New";
});
var InProcItems = items.filter(function(ItemStatus) {
return ItemStatus.Status == "In Process";
});
var CompItems = items.filter(function(ItemStatus) {
return ItemStatus.Status == "Completed";
});
MyDataset.push(NewItems.length);
MyDataset.push(InProcItems.length);
MyDataset.push(CompItems.length);
console.log(MyDataset);
createChar(MyDataset);
}
function createChar(dataset) {
const labels = ['New', 'Inproccess', 'Completed'];
const data = {
labels: labels,
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data:dataset
}]
};
const config = {
type: 'bar',
data: data,
options: {}
};
const myChart = new Chart(
document.getElementById('myChart'),
config
);
}
</script>
You specify 3 labels and provide 7 element in data.
To resolve your problem, try with a simple config
const config = {
type: 'bar',
labels: labels // Your array of label
data: {
datasets: [{
data: [1, 2, 3], // Random data
}],
}
};
When that display something, try to add complexity.
By guessing, I believe you want something like that
const config = {
type: 'bar',
labels: labels, // Your array of label
data: {
datasets: [{
data: [
{x:'New', y:1},{x:'Completed', y:10},{x:'Inproccess', y:100},
{x:'New', y:2},{x:'Completed', y:20},{x:'Inproccess', y:200},
{x:'New', y:3},{x:'Completed', y:30},{x:'Inproccess', y:300},
]
}]
}
};
It's hard to help you as you didn't specify what kind of result chart you want to see...
your code working (snippet)
const labels = ['New', 'Completed', 'Inproccess'];
const config = {
type: 'bar',
labels: labels,
data: {
datasets: [{
label : 'Chart1',
data: [
{x:'New', y:1},{x:'Completed', y:10},{x:'Inproccess', y:100},
{x:'New', y:2},{x:'Completed', y:20},{x:'Inproccess', y:200},
{x:'New', y:3},{x:'Completed', y:30},{x:'Inproccess', y:300},
]
}]
}
};
const myChart = new Chart(
document.getElementById('myChart'),
config
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<div>
<canvas id="myChart"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
I'm doing a project which is to extract data from python and show it in jsp dashboard.
I'm trying to load a json file to chartjs but it's not giving result
<script>
$.getJSON("resources/json_test.json", function(data) {
var labels = data.department.map(function(e) {
return e[1];
});
var data = data.volunteer.map(function(e) {
return e[1];
});
var context = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(context, {
type : 'bar',
data : {
labels : labels,
datasets : [ {
label : 'volunteer',
lineTension : 0.1,
data : data,
backgroundColor : "rgba(255, 99, 132, 0.2)"
}]
}
});
});
{"department":{"0":"IT","1":"Math","2":"English","3":"Software","4":"Game"},"volunteer":{"0":409,"1":1781,"2":476,"3":550,"4":562}}
To call .map() the datastructure needs to be an array, and since yours are objects it aint working, if you change your code to this it should work:
const labels = Object.values(data.department)
const parsedData = Object.values(data.volunteer)
const context = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(context, {
type: 'bar',
data: {
labels: labels,
datasets: [ {
label: 'volunteer',
lineTension: 0.1,
data: parsedData,
backgroundColor: "rgba(255, 99, 132, 0.2)"
}]
}
});
This is my script inside the script where I init the charts
JavaScript
$(document).ready( () => {
setInterval( () => {
var sensorUpdatedData = new XMLHttpRequest();
sensorUpdatedData.onreadystatechange = () => {
if(sensorUpdatedData.readyState === 4) {
if(sensorUpdatedData.status === 200) {
console.log("ready");
var Data = JSON.parse(sensorUpdatedData.responseText);
console.log(Data);
valueTemp = Data.temperature;
valueHum = Data.humidity;
valueSmoke = Data.smoke;
reading_time = Data.reading_time;
reading_time_hour = Data.reading_time_hour;
myChartTemp.update();
myChartHum.update();
myChartSmoke.update();
myChartData.update();
} else {
alert('Error Code: ' + sensorUpdatedData.status);
alert('Error Message: ' + sensorUpdatedData.statusText);
}
}
}
sensorUpdatedData.open('POST', 'data.php', true);
sensorUpdatedData.send();
}, 5000);
});
All the values are updating correctly(I tested with some console.log)
This is how I created one of the charts:
var ctxTempChart = document.getElementById("chartLineTemp").getContext("2d");
var gradientStrokeTempChart = ctxTempChart.createLinearGradient(0, 230, 0, 50);
gradientStrokeTempChart.addColorStop(1, 'rgba(29,140,248,0.2)');
gradientStrokeTempChart.addColorStop(0.4, 'rgba(29,140,248,0.0)');
gradientStrokeTempChart.addColorStop(0, 'rgba(29,140,248,0)'); //blue colors
var dataTemp = {
labels: reading_time_hour,
datasets: [{
label: "Temperature",
fill: true,
backgroundColor: gradientStrokeTempChart,
borderColor: '#1f8ef1',
borderWidth: 2,
borderDash: [],
borderDashOffset: 0.0,
pointBackgroundColor: '#1f8ef1',
pointBorderColor: 'rgba(255,255,255,0)',
pointHoverBackgroundColor: '#1f8ef1',
pointBorderWidth: 20,
pointHoverRadius: 4,
pointHoverBorderWidth: 15,
pointRadius: 4,
data: valueTemp,
}]
};
var myChartTemp = new Chart(ctxTempChart, {
type: 'line',
data: dataTemp,
options: gradientBarChartConfigurationTempSmall
});
HTML
<canvas id="chartLineTemp"></canvas>
Everything seem to work fine but I don't know how to display the updated data.
The vavalueTemp, valueHum... are declareted globally, at the beggining of the script
UPDATE
If I add this:
myChartTemp.data.labels = reading_time_hour;
myChartTemp.data.datasets[0].data = valueTemp;
window.myChartTemp.update();
I got this(with document also): Cannot read property 'update' of undefined at XMLHttpRequest.sensorUpdatedData.onreadystatechange
And if I go like this:
myChartTemp.data.labels = reading_time_hour;
myChartTemp.data.datasets[0].data = valueTemp;
myChartTemp.update();
(without window or document in front)I got ths: TypeError: Object.defineProperty called on non-object
Have you tried accessing the update function as a DOM object?
window.myChartTemp.update(); or
document.myChartTemp.update();
The problem was that I was passing an object and it expected an array. My var Data is a single JSON object containing multiple JSON objects. After I applied valueTemp = JSON.parse(Data.temperature); , it returns an array of temperature values, exactly what I needed.
In the code below I am making a chartJS chart using database data, this is being done via a submit button which looks like this:
function showWhatSelected(str) {
$('#select2').hide();
$('#select3').hide();
if (str == "") {
document.getElementById("select1").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("select1").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","../controller/teamleiderController.php?action=whatToShow&value="+ str,true);
xmlhttp.send();
}
}
After that the AJAX runs which makes the new chart when a change has been detected in the submit button:
$.ajax({
url: "../controller/teamleiderController.php?action=select2JSON&value="+ str +"",
method: "GET",
success: function(data) {
console.log(data);
var label = ['aanwezig', 'afwezig'];
var aanwezigheid = [];
for(var i in data) {
aanwezigheid.push(data[i].aanwezig, data[i].afwezig, );
}
var chartdata = {
labels: label,
datasets : [
{
backgroundColor: ['rgba(0, 65, 140, 0.8)', 'rgba(215, 165, 0, 0.8)'],
borderColor: 'rgba(0, 0, 0, 0)',
hoverBackgroundColor: ['rgba(0, 65, 140, 1)', 'rgba(215, 165, 0, 1)'],
hoverBorderColor: 'rgba(200, 200, 200, 0)',
data: aanwezigheid
}
]
};
var option = {
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'pie',
data: chartdata,
options:option
});
},
error: function(data) {
console.log(data);
}
});
}
My problem is that my chart is ghosting, it keeps showing previous data, is there any way I can fix this? I have tried .destroy() and .clear() but they both don't seem to work...
You indeed need to use .destroy() method to remove any previous instance of chart before making a new one.
Perhaps, you were using the .destroy() method in an inappropriate manner, which made it non-effective.
Here's how you could properly remove / destroy any previous instance of chart, before creating a new one ...
var meta = barGraph && barGraph.data && barGraph.data.datasets[0]._meta;
for (let i in meta) {
if (meta[i].controller) meta[i].controller.chart.destroy();
}
affix the above code before initiating your chart
note: barGraph must be a global variable.
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩
var barGraph;
function init(str) {
$.ajax({
url: "https://istack.000webhostapp.com/json/" + str + ".json",
method: "GET",
success: function(data) {
console.log(data);
var label = ['aanwezig', 'afwezig'];
var aanwezigheid = [];
for (var i in data) {
aanwezigheid.push(data[i].aanwezig, data[i].afwezig);
}
var chartdata = {
labels: label,
datasets: [{
backgroundColor: ['rgba(0, 65, 140, 0.8)', 'rgba(215, 165, 0, 0.8)'],
borderColor: 'rgba(0, 0, 0, 0)',
hoverBackgroundColor: ['rgba(0, 65, 140, 1)', 'rgba(215, 165, 0, 1)'],
hoverBorderColor: 'rgba(200, 200, 200, 0)',
data: aanwezigheid
}]
};
var option = {responsive: false};
// destroy previous chart
var meta = barGraph && barGraph.data && barGraph.data.datasets[0]._meta;
for (let i in meta) {
if (meta[i].controller) meta[i].controller.chart.destroy();
}
// make new chart
var ctx = $("#mycanvas");
barGraph = new Chart(ctx, {
type: 'pie',
data: chartdata,
options: option
});
},
error: function(data) {
console.log(data);
}
});
}
body{overflow:hidden}button{margin-left: 45px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<button onclick="init('t1')">Dataset 1</button>
<button onclick="init('t2')">Dataset 2</button><br>
<canvas id="mycanvas" height="180"></canvas>