Undefined values in chart.js from json - javascript

i am working on showing data in a bar chart with chart.js . my json response is already ready there but chart says its undefined values.
here is jquery with json
$(document).ready(function(){
$.ajax({
url: "<?php base_url();?>/charts/getsome",
method: "GET",
success: function(data) {
console.log(data);
var month = [];
var customers = [];
for(var i in data) {
month.push("Customer in" + data[i].apply_month);
customers.push(data[i].no_customers);
}
var chartdata = {
labels: month,
datasets : [
{
label: 'monthly customers',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: customers
}
]
};
// alert(chartdata);
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});
below is a snap for json response in console
And here is also a snap for chart with error
Please guide me where i am wrong. Thanks

You are getting response as a string. you should parse using JSON.parse(data)
success: function(data) {
console.log(data);
data = JSON.parse(data)
//the rest of your code
}

Related

Unable to render two datasets from the controller in View

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

json file to charts

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)"
}]
}
});

Chart.js with data from database

since 2 hours I'm trying a simple thing: displaying data from database with Chart.js. I've checked like 4 tutorials, viewed 3 SO-Threads, but nothing is working as intented to. Don't know if its just a minor problem or what the problem is...
So what I'm trying is the following:
stats.php:
<script>
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
</script>
<script>
$(document).ready(function(){
$.ajax({
url: "stats_api.php",
method: "GET",
success: function(data) {
console.log(data);
var chart = new Chart(document.getElementById("pie-chart"), {
type: 'pie',
data: {
labels: data,
datasets: [{
label: "Anzahl Asservate",
backgroundColor: [getRandomColor(),getRandomColor(),getRandomColor(),getRandomColor(),getRandomColor(),getRandomColor(),getRandomColor(),getRandomColor(),getRandomColor(),getRandomColor()],
data: [1,2,3,4,5,6,7,8,9,10],
}]
},
options: {
title: {
display: true,
text: 'Kategorien-Verteilung der Asservate'
}
}
});
}
});
});
</script>
stats_api.php:
<?php
require 'databaseConnection.php';
$datumStart = "2010-12-19 08:38:32";
$datumEnde = "2019-12-19 08:38:32";
$v_rp_ass_kat = $database->query("
select s.* from (select #DatumStart:='$datumStart',#DatumEnde:='$datumEnde') parm , v_rp_ass_kat s;")->fetchAll();
$labels = [];
foreach($v_rp_ass_kat as $element){
array_push($labels, $element[2]);
}
echo json_encode($labels);
The json_encode is returning this:
["Mobiltelefon","Smartphone","SIM-Karte","Tablet","Navigationsger\u00e4t","USB-Stick","Speicherkarte","PC","Notebook","Festplatte"]
With that, I'm getting the error saying data.labels.map is not a function.
I also tried it without the foreach in php, instead a json_encode of $v_rp_ass_kat and then do a
labels = [];
for(var i in data){
labels.push(data[i].kategorie);
}
But this somehow splits the array into single letters, so instead of 10 labels with one word each, I get like 100 labels, one for every letter of the json array...
What do I do wrong?
I reckon, you're getting the response as a string and passing it to the labels property, while it expects an array of strings. (same mistake in your fiddle as well)
To convert that response string to an array, you can use JSON.parse()
...
data: {
labels: JSON.parse(data),
...
also, you should use the chart.js version 2.x, as you're using it's syntax.
Working fiddle - https://jsfiddle.net/bf4v9272/5/
https://www.dyclassroom.com/chartjs/chartjs-how-to-draw-bar-graph-using-data-from-mysql-table-and-php
$(document).ready(function(){
$.ajax({
url: "http://localhost/chartjs/data.php",
method: "GET",
success: function(data) {
console.log(data);
var player = [];
var score = [];
for(var i in data) {
player.push("Player " + data[i].playerid);
score.push(data[i].score);
}
var chartdata = {
labels: player,
datasets : [
{
label: 'Player Score',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: score
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});
i hope you will Get

Javascript not getting data from PHP?

I'm trying to plot some data using javascript , ajax and php .
This is my test.php :
$query=sprintf("SELECT COUNT( `cases_title`) as count ,`cases_title` FROM `classifies` GROUP BY `cases_title`");
$result=$mysqli->query($query);
$data=array();
foreach($result as $row){
$data[]=$row;
}
$result->close();
$mysqli->close();
print json_encode($data);
?>
I printed the output and it was :
[{"count":"7","cases_title":"ANGINA"},{"count":"1","cases_title":"ASTHMA"},{"count":"4","cases_title":"MI"}]
So I suppose test.php is working.
This is my app.js :
$(document).ready(function(){
$.ajax({
url: "http://localhost/final/test.php",
method: "GET",
success: function(data) {
console.log(data);
var cas=[];
var cou=[];
// document.write(data);
for(var i in data) {
cas.push(data[i].cases_title);
cou.push(data[i].count);
}
console.log(cou);
var chartdata = {
labels: cas,
datasets : [
{
label: 'Count',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: cou
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});
document.write(data) in app.js returns : [{"count":"7","cases_title":"ANGINA"},{"count":"1","cases_title":"ASTHMA"},{"count":"4","cases_title":"MI"}]
However the arrays aren't being filled. They show as undefined . The url to test.php is correct.
What is causing the arrays cou and cas to not be filled? I couldn't figure it out.
you have to parse the response as json with JSON.parse(data) or the other side arround JSON.stringify before transferring valid json data via network.

ChartJS remove previous chart when making new one

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>

Categories