I have a bar graph that I'm attempting to create with chart.js that takes a PHP array and loads via ajax. I am able to load the data with ajax (verified in the console) but I cannot get the data in the graph - here is the data in the console:
I have not received any error messages so I'm perplexed at this point. Here is all of the code:
HTML
<?php
include 'connect.php';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
</canvas><canvas id="myChart"></canvas>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="javascript/charts.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
</body>
JS
$(document).ready(function(){
$.ajax({
url: "prod_agg.php",
method: "GET",
success: function(data) {
console.log(data);
var date = [];
var output = [];
for(var i in data) {
date.push(data[i].date);
output.push(data[i].output);
}
var chartdata = {
labels: date,
datasets : [
{
label: 'Date',
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: output
}
]
};
var ctx = $("#myChart");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});
I receive an empty graph:
Any help on this issue would be greatly valued!
The reason it's not working is because, you are getting the response data as a JSON string not JSON object.
So, to make it work with ChartJS, you need to parse it first, using JSON.parse() method ...
$(document).ready(function() {
$.ajax({
url: "prod_agg.php",
method: "GET",
success: function(data) {
console.log(data);
var data = JSON.parse(data); //parse JSON string
var date = [];
var output = [];
...
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'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
});
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
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.
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
}