How to correctly passed php mysql data to ChartJs - javascript

I want to be able to produce bar chart and pie charts using ChartJs. I'm using php and mysql to get the data. The bar chart that I want to produce is a chart that shows the stats of students who are male or female and the sum of students also. Here is an example of how I want the result to appear:
It may not be exactly like it, but I feels it gives an idea. I'm problems with my code which I don't seem to understand, because I'm a novice to ChartJs and is just trying it out, since morris.js isn't being fully supported. Here is how my code looks:
Html
<div class="box box-success">
<div class="box box-header with-border">
<h3 class="box-title">Student Chart</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
</button>
<button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
</div>
<div class="box-body">
<canvas id="mycanvas" style="height:230px;"></canvas>
</div>
</div>
Script:
$.ajax({
url: 'data.php',
type: 'GET',
success:function(data){
console.log(data);
var male = [];
var female = [];
for(var count in data){
male.push(data[count].male);
female.push(data[count].female);
}
var chartdata = {
labels: male,
datasets: [
{
label: 'Student Gender',
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:female
}
]
};
var ctx = $('#mycanvas');
var barGraph = new Chart(ctx, {
type:'bar',
data: chartdata
});
},
error:function(data){
console.log(data);
}
});
data.php
$query = "SELECT
SUM(CASE WHEN gender = 'Male' THEN 1 ELSE 0 END) as Male,
SUM(CASE WHEN gender = 'Female' THEN 1 ELSE 0 END) as Female
FROM students";
$output = array();
if ($result = mysqli_query($connection, $query)) {
# code...
foreach ($result as $row) {
# code...
$output[] = $row;
}
} else {
die("There was a problem". mysqli_error($connection));
}
echo json_encode($output);
Here is the result I'm getting from the console:
[{"Male":"5","Female":"2"}]
Will appreciate suggestion on how I can make it better and do the same for pie chart also.
Based on what I've done this is how my chart is displaying:
Note Please ignored the frequency on the photo.

Would suggest you to change your sql query to following.
$query = "select gender,count(gender) as count from students group by gender";
$output = array();
if ($result = mysqli_query($connection, $query)) {
# code...
foreach ($result as $row) {
# code...
$output[] = $row;
}
} else {
die("There was a problem". mysqli_error($connection));
}
echo json_encode($output);
script:
$.ajax({
url: 'data.php',
type: 'GET',
success:function(data){
console.log(data);
var gender = [];
var sum = [];
for(var count in data){
gender.push(data[count].gender);
sum.push(data[count].total);
}
var chartdata = {
labels: gender,
datasets: [
{
label: 'Student Gender',
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:sum
}
]
};
var ctx = $('#mycanvas');
var barGraph = new Chart(ctx, {
type:'bar',
data: chartdata
});
},
error:function(data){
console.log(data);
}
});

I realize that the problem was with my script. Big thanks to #milan kumar for helping with the query. What was missing was specification of the type of data I was sending to ajax. All I had to do was to add the dataType with value 'json' before the success function, and it work perfectly. This is how the code should look:
script:
$.ajax({
url: 'data.php',
type: 'GET',
// this was what I needed to make it work.
dataType: 'json',
success:function(data){
var gender = [];
var sum = [];
for(var i in data){
gender.push(data[i].gender);
sum.push(data[i].total);
}
var ChartData = {
labels: ['Student Gender'],
datasets: [
{
label: gender[0],
fillColor: "rgba(210, 214, 222, 1)",
strokeColor: "rgba(210, 214, 222, 1)",
pointColor: "rgba(210, 214, 222, 1)",
pointStrokeColor: "#c1c7d1",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data:sum[0]
},
{
label: gender[1],
fillColor: "rgba(60,141,188,0.9)",
strokeColor: "rgba(60,141,188,0.8)",
pointColor: "#3b8bba",
pointStrokeColor: "rgba(60,141,188,1)",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(60,141,188,1)",
data:sum[1]
}
]
};
});
I have added some optional attributes to beautify my chart.

Related

I want to change color of individual bar of bar graph

I am getting data from mysql using php to populate the array and then using that result to fill chart data. I want to change the color of the bars which are greater than 50. I tried a few examples that are already on the stack-overflow, however I was unable to solve my problem. That is why I am now asking this question.
$(document).ready(function() {
$.ajax({
url: "http://localhost:8080/chartjs/data.php",
method: "GET",
success: function(data) {
console.log(data);
var player = [];
var score = [];
for (var i in data) {
player.push(data[i].y);
score.push(data[i].x);
}
var chartdata = {
labels: player,
datasets: [{
label: 'Records from mysql',
backgroundColor: 'rgb(92, 95, 102)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(30, 0, 200)',
hoverBorderColor: 'rgba(200, 200, 197)',
data: score
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
colors: {
data: function(score) {
return (score.value >= 45) ? '#00ff00' : '#f90411';
}
},
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});
#chart-container {
width: 640px;
height: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>
<div id="chart-container">
<canvas id="mycanvas"></canvas>
</div>
From what I could figure out is that your question is mostly related to the usage of chart.js. My solution to your problem would look like the following:
//Load your data (obviously this is a hardcoded example, you could use any backend code like PHP):
let data = [12, 19, 74, 38, 45, 62];
//Insantiate fields you would like to use, such as `colors` for background color and `borderColors` for, you guessed it, the color of the borders:
let colors = [];
let borderColors = [];
//Set the field values based on value (this would be your logic):
$.each(data, function(index, value) {
//When the value is higher than 45, set it to given color, else make them the other color (in the example the bars would appear red-ish):
if(value > 45) {
colors[index] = "rgba(0, 255, 0, 0.2)";
borderColors[index] = "rgba(0, 255, 1)";
}
else {
colors[index] = "rgba(249, 4, 17, 0.2)";
borderColors[index] = "rgba(249, 4, 17, 1)";
}
});
//Any code related to creating the chart with the bars (you could find any documentation regarding this code on the homepage of Chart.js):
let ctx = document.getElementById('myChart');
let myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['1', '2', '3', '4', '5', '6'],
datasets: [{
label: 'Records from mysql',
//Populate your fields here:
data: data,
backgroundColor: colors,
borderColor: borderColors,
hoverBackgroundColor: 'rgba(30, 0, 200)',
hoverBorderColor: 'rgba(200, 200, 197)',
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
#chart-container {
width: 640px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>
<div id="chart-container">
<canvas id="myChart"></canvas>
</div>
JSFiddle
I applied some code I found on the following post on Github:
$.each(data, function(index, value) {
//When the value is higher than 45, set it to given color, else make them the other color (in the example the bars would appear red-ish):
if(value > 45) {
colors[index] = "rgba(0, 255, 0, 0.2)";
borderColors[index] = "rgba(0, 255, 1)";
}
else {
colors[index] = "rgba(249, 4, 17, 0.2)";
borderColors[index] = "rgba(249, 4, 17, 1)";
}
});
If anyone knows a more clean solution, please let me know in the comments.

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.

Undefined values in chart.js from json

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
}

Chart.js, PHP and radar chart labels

I want to create dynamic graphics directly linked to a PostgreSQL DB.
For the moment, I succeeded on bar diagrams, but it is complicated on other types of diagram including the radar.
My goal is to get an IRIS (iri_code), a profile on 3 relative variables (txact, txchom, pop_txevol) as in the image below
what I want
First of all, here is my PHP (data_radar.php)
<?php
$dbconn = pg_connect("host='' dbname='' user='' password=''")
or die('Erreur de connexion'.pg_last_error());
$query = "SELECT iri_code, iri_pop_txevol, iri_txact, iri_txchom FROM demo_geo.demo_iris_view WHERE iri_code = '352380801'";
$result = pg_query($query) or die('Query failed: ' . pg_last_error());
$array = array();
while ($row = pg_fetch_array($result, null, PGSQL_ASSOC)) {
$array[] = $row;
}
$data=json_encode($array);
echo $data;
pg_free_result($result);
pg_close($dbconn);
?>
It works, here is the json output
[{"iri_code":"352380801","iri_pop_txevol":"3.1","iri_txact":"69.5","iri_txchom":"9.8"}]
But I don't understand how to set the graphic on the JS part. Is the structure of the json good?
$(document).ready(function() {
$.ajax({
url : "http://localhost/test_a/data_radar.php",
type : "GET",
dataType: 'json',
success : function(data){
console.log(data);
var irisA = [];
var txact = [];
var txchom = [];
var txevol = [];
for(var i in data) {
irisA.push(data[i].iri_code);
txact.push(data[i].iri_txact);
txchom.push(data[i].iri_txchom);
txevol.push(data[i].iri_pop_txevol);
}
var ctx1 = $("#canvas-radar");
var data1 = {
labels : [txact, txchom, txevol],
datasets : [
{
label : "IRIS",
data : irisA,
backgroundColor: "rgba(179,181,198,0.2)",
borderColor: "rgba(179,181,198,1)",
pointBackgroundColor: "rgba(179,181,198,1)",
pointBorderColor: "#fff",
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "rgba(179,181,198,1)"
}
]
};
var options = {
title : {
display : true,
position : "top",
text : "Radar test",
fontSize : 14,
fontColor : "#111"
},
legend : {
display : true,
position : "bottom"
}
};
var chart1 = new Chart( ctx1, {
type : "radar",
data : data1,
options : options
});
},
error : function(data) {
console.log(data);
}
});
});
Here is what it gives
radar chart bug
I have searched forums but I confess that I am not yet comfortable, if someone can enlighten me to accelerate my learning it would be very very nice
Thank you in advance and good day !
Here's how you could accomplish that ...
let json = [{ "iri_code": "352380801", "iri_pop_txevol": "3.1", "iri_txact": "69.5", "iri_txchom": "9.8" }, { "iri_code": "352380703", "iri_pop_txevol": "23.0", "iri_txact": "15.3", "iri_txchom": "29.8" }];
let label = [];
let data = [];
// generate label and data dynamically
json.forEach(e => {
label.push(e.iri_code);
data.push([+e.iri_pop_txevol, +e.iri_txact, +e.iri_txchom]);
});
let ctx = document.querySelector('#canvas').getContext('2d');
let chart = new Chart(ctx, {
type: 'radar',
data: {
labels: ['txevol', 'txact', 'txchom'],
datasets: [{
label: label[0],
data: data[0],
backgroundColor: 'rgba(0,119,204,0.2)',
borderColor: 'rgba(0,119,204, 0.5)',
borderWidth: 1,
pointBackgroundColor: 'rgba(0, 0, 0, 0.5)'
}, {
label: label[1],
data: data[1],
backgroundColor: 'rgba(255, 0, 0 ,0.15)',
borderColor: 'rgba(255, 0, 0 ,0.45)',
borderWidth: 1,
pointBackgroundColor: 'rgba(0, 0, 0, 0.5)'
}]
},
options: {
title: {
display: true,
position: "top",
text: "Radar test",
fontSize: 14,
fontColor: "#111"
},
legend: {
display: true,
position: "bottom"
},
scale: {
pointLabels: {
fontSize: 11
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="canvas"></canvas>

Is it possible to add individual labels to Chart.JS bars?

I have a fully functional Chart.JS Barchart which loads as intended, however I would like to add the username to each bar which is associated to them so administrators (who can see all entries) can distinguish between them.
function BarChart(data) {
var barChartData = {
labels: data.Month,
datasets: [
{
label: 'Weight (kg)',
fillColor: "rgba(220,220,220,0.5)",
backgroundColor: "rgba(46, 44, 211, 0.7)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: data.Weight
},
{
label: 'Steps',
fillColor: "rgba(0,0,0,0.5)",
backgroundColor: "rgba(215, 44, 44, 0.7)",
highlightFill: "rgba(0,0,0,0.5)",
highlightStroke: "rgba(0,0,0,0.5)",
data: data.Steps
}
]
}
var ctx = document.getElementById("barchart").getContext("2d");
window.myBar =new Chart(ctx, {
type: 'bar',
data: barChartData,
options: { responsive: true }
});
I have successfully passed through the Usernames and they can be called by using data.User, however when I append this to the Steps or Weight label, I end up with "Steps for: admin,admin,admin" (since I have three entries, all from admin).
Is it possible to have it so each bar has the username it belongs to?
Maybe not quite what you asked for, but you could add it to the tooltip.
options: {
tooltips:{
callbacks: {
afterLabel: function(e){return "added By:" +data.User[e.datasetIndex][e.index]}
}
}
}
https://jsfiddle.net/r71no58a/7/

Categories