Related
I want to create a bar chart using chartjs,PHP and MySql. After querying the database to get product details as a json object, now I want to iterate over the array and add product_name and price into new arrays, of which I get undefined. What might be wrong to my code?
$(document).ready(function(){
$.ajax({
url: "../controller/products-chart-data.php",
method: "GET",
success: function(data){
console.log(data);
var product = [];
var price = [];
for (var i in data) {
product.push(data[i].product_name);
price.push(data[i].price);
}
var chartData = {
labels: product,
datasets: [
{
label: "Product Price",
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: price
}
]
};
var context = $("#products-chart");
var barGraph = new Chart(context, {
type: 'bar',
data: chartData
});
},
error: function(data){
console.log(data);
}
})
})
PHP code for the database query:
<?php
$conn = mysqli_connect('localhost', 'root', '', 'shopping_cart_with_paypal');
$getAllproductsQuery = $conn->query("SELECT * FROM tbl_products");
$data = array();
foreach ($getAllproductsQuery as $row) {
$data[] = $row;
}
$getAllproductsQuery->close();
$conn->close();
print json_encode($data);
Sample data:
[{"id":"3","product_name":"Travel
bag","price":"5000","category_id":"1","product_image":"travel-
bag.jpeg","average_rating_id":"3","description":"Lather travel bag, found in
different sizes","product_code":"203"},{"id":"4","product_name":"Jewel
Box","price":"6000","category_id":"4","product_image":"jewel-
box.jpeg","average_rating_id":"5","description":"Modern jewel box straight
dubai","product_code":"204"},{"id":"5","product_name":"Wooden
Dolls","price":"9000","category_id":"5","product_image":"wooden-
dolls.jpeg","average_rating_id":"3","description":"wooden dolls made of pure
woods","product_code":"205"}]
I am using chart.js to create graphs. I'm trying to generate a graph for bdi vs date for specific customers based on their unique IDs. When you visit customer.php that specific customers ID can be found in the URL. I'm trying to request the bdi vs. date data from data.php and query it to generate a line graph.
This is what I have so far:
Customer.php (Chart.js Code);
$(document).ready(function(){
$.ajax({
url: "charts/data.php",
method: "GET",
success: function(data) {
console.log(data);
var bdi = [];
var date = [];
for(var i in data) {
date.push( data[i].date);
bdi.push(data[i].bdi);
}
var chartdata = {
labels: date,
datasets : [
{
label: 'BDI',
backgroundColor: 'rgba(239, 243, 255, 0.75)',
borderColor: 'rgba(84, 132, 255, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: bdi
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'line',
data: chartdata,
options: {
responsive: true,
legend: {
position: 'bottom',
},
scales: {
yAxes: [{
ticks: {
fontColor: "rgba(0,0,0,0.5)",
fontStyle: "bold",
beginAtZero: true,
maxTicksLimit: 5,
padding: 20
},
gridLines: {
drawTicks: false,
drawBorder: false,
}
}],
xAxes: [{
gridLines: {
zeroLineColor: "transparent",
display: false
},
ticks: {
padding: 20,
fontColor: "rgba(0,0,0,0.5)",
fontStyle: "bold"
}
}]
},
tooltips: {
backgroundColor: 'rgba(255,255,255)',
titleFontColor: 'rgb(184,189,201)',
bodyFontColor: 'black',
displayColors: false,
borderColor: 'rgb(214,217,225)',
borderWidth: 1,
caretSize: 5,
cornerRadius: 2,
xPadding: 10,
yPadding: 10
}
}
});
},
error: function(data) {
console.log(data);
}
});
});
data.php:
<?php
session_start();
//setting header to json
header('Content-Type: application/json');
require_once '../config/config.php';
require_once '../includes/auth_validate.php';
$cid = htmlentities ($_GET['customer_id']);
//get connection
//query to get data from the table
$sql = sprintf("SELECT treatment_log.bdi, treatment_log.date FROM treatment_log WHERE treatment_fk = ? ORDER BY created_at");
$stmt = mysqli_stmt_init($conn);
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_bind_param($stmt, "i", $cid);
mysqli_stmt_execute($stmt);
$data = array();
mysqli_stmt_bind_result($stmt, $bdi, $date);
while(mysqli_stmt_fetch($stmt)) {
$data[] = array('bdi' => $bdi, 'date' => $date);
}
//free memory associated with result
$result->close();
//now print the data
print json_encode($data);
I cant seem to generate a graph. I'm not sure what I'm doing wrong!
Example of data to be graphed:
[{"bdi":"4","date":"2018-07-11"},{"bdi":"1","date":"2018-07-21"},{"bdi":"5","date":"2018-07-21"},{"bdi":"34","date":"2018-07-21"},{"bdi":"34","date":"2018-07-21"},{"bdi":"3","date":"2018-07-22"},{"bdi":"2","date":"2018-07-23"},{"bdi":"12","date":"2018-07-23"},{"bdi":"3","date":"2018-07-24"},{"bdi":"2","date":"2018-07-25"},{"bdi":"12","date":"2018-07-30"},{"bdi":"3","date":"2018-07-30"},{"bdi":"4","date":"2018-07-30"},{"bdi":"11","date":"2018-07-30"}]
I'm trying to use ChartJs and pull data from our Oracle database. I have followed the documentation as best I could and tried to adapt them for my oci output but I can't seem to get the data pulled.Here is my fetch array from data.php:
oci_execute($query);
$data = array();
while($row = oci_fetch_array($query, OCI_ASSOC)) {
$data[] = $row;
}
print json_encode($data);
Which outputs this:
[{"DT":"01-FEB-18","SHIFTS":"FIRST","TOTAL":"6","IP":"5","DOMESTIC":"2","P_RICO":"3","EXPORTS":"1"},{"DT":"31-JAN-18","SHIFTS":"SECOND","TOTAL":"66","DOMESTIC":"49","P_RICO":"4","EXPORTS":"13"},{"DT":"31-JAN-18","SHIFTS":"FIRST","TOTAL":"55","DOMESTIC":"30","P_RICO":"1","EXPORTS":"24"},{"DT":"30-JAN-18","SHIFTS":"SECOND","TOTAL":"52","DOMESTIC":"34","P_RICO":"10","EXPORTS":"8"},{"DT":"30-JAN-18","SHIFTS":"FIRST","TOTAL":"69","DOMESTIC":"55","P_RICO":"2","EXPORTS":"12"},{"DT":"29-JAN-18","SHIFTS":"SECOND","TOTAL":"61","DOMESTIC":"41","P_RICO":"10","EXPORTS":"10"},{"DT":"29-JAN-18","SHIFTS":"FIRST","TOTAL":"48","DOMESTIC":"43","P_RICO":"2","EXPORTS":"3"},{"DT":"28-JAN-18","SHIFTS":"SECOND","TOTAL":"53","DOMESTIC":"44","P_RICO":"1","EXPORTS":"8"},{"DT":"28-JAN-18","SHIFTS":"FIRST","TOTAL":"53","DOMESTIC":"43","P_RICO":"3","EXPORTS":"7"}]
The PHP variables that I'm concerned with are DT, SHIFTS, and TOTAL. On my index.php I have this ajax call to get the variables:
$.ajax({
url: "data.php",
method: "GET",
success: function(data) {
console.log(data);
var shifts = [];
var total = [];
var dt = [];
for(var i in data) {
shifts.push("Shift " + data[i].SHIFTS);
total.push(data[i].TOTAL);
dt.push(data[i].DT);
}
var chartdata = {
labels: shifts,
datasets : [
{
label: 'Shipments Complete',
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: total
}
]
};
var ctx = $("#ships");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
when I run index.php it just says that the variables are undefined.Can anyone point out where I'm going wrong?
Hello :) (I'm novice and I learn on the job),
I work with Chart.js, jQuery, PostgreSQL
Currently I have a bar chart directly linked to PostgreSQL database.
I'd like to add a dropdown to allow the user to select a "zone", which would dynamically update the chart.
Each "zone" has different variables: population, salaries (number of employees in english), etc.
Here is the PHP
<?php
$dbconn = pg_connect("")
or die('Erreur de connexion'.pg_last_error());
$query = "SELECT id, zone_nom, zone_pop, zone_salaries FROM table";
$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);
?>
I get the following array
[{"id":"1","zone_nom":"test ","zone_pop":"36105","zone_salaries":"15279"},{...],{...}]
Then I generate a dropdown dynamically populated by my table
But I'm stuck on how to pass the selected values in the chart (and then make sure the chart gets refreshed depending on the choice in the dropdown)
<html>
<head>
<title>Liste déroulante dynamique</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/Chart.min.js"></script>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet/v1.0.3/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet/v1.0.3/leaflet-src.js"></script>
<script type="text/javascript">
function Zone() {
$('#zone-select').empty();
$('#zone-select').append("<option>Chargement</option>");
$.ajax({
type: "POST",
url: "http://localhost/data.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
$('#zone-select').empty();
$('#zone-select').append("<option value='0'>-- Select zone --</option>");
$.each(data,function(i, item){
$('#zone-select').append('<option value='+data[i].zone_pop+'>'+data[i].zone_nom+'</option>');
});
$("#zone-select").change(function(){
var value = $("#zone-select option:selected").val(); // Value of selected option
console.log('Value: '+value);
});
// How to link the dropdown and the chart ?
var zoneNom = [];
var zonePop = [];
for(var i in data) {
zoneNom.push(data[i].zone_nom);
zonePop.push(data[i].zone_pop);
zoneSalaries.push(data[i].zone_salaries)
}
var chartdata = {
labels: zoneNom,
datasets : [
{
label: 'Population',
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: zonePop
},
{
label: 'Salaries',
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: zoneSalaries
}
]
};
var option = {};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata,
options: option
});
var myBarChart;
},
complete: function(){
}
});
}
$(document).ready(function(){
Zone();
});
</script>
</head>
<body>
<select id="zone-select"></select>
<div id="chart-container">
<canvas id="mycanvas"></canvas>
</div>
</body>
</html>
The value of the choice is returned
$("#zone-select").change(function(){
var value = $("#zone-select option:selected").val(); // Value of selected option
console.log('Value: '+value);
});
I am looking for but I can not find the solution for now (probably not very complicated)
Thank you in advance for your help
You could accomplish this using the following on change event handler function for your dropdown menu ...
$("#zone-select").change(function() {
var nom = $("#zone-select option:selected").text(); // name of selected option
var index = zoneNom.indexOf(nom);
var new_labels = [zoneNom[index]];
var new_data1 = [zonePop[index]];
var new_data2 = [zoneSalaries[index]];
barGraph.data.labels = new_labels;
barGraph.data.datasets[0].data = new_data1;
barGraph.data.datasets[1].data = new_data2;
barGraph.update(); // update chart
});
and, if you wish to select the first option by default, use ...
$("#zone-select").val(zonePop[0]).trigger('change');
working example
function Zone() {
$('#zone-select').empty();
$('#zone-select').append("<option>Chargement</option>");
$.ajax({
type: "GET",
url: "https://istack.000webhostapp.com/json/t9.json",
dataType: "json",
success: function(data) {
//console.log(data)
$('#zone-select').empty();
$('#zone-select').append("<option value='0'>-- Select zone --</option>");
$.each(data, function(i, item) {
$('#zone-select').append('<option value=' + data[i].zone_pop + '>' + data[i].zone_nom + '</option>');
});
$("#zone-select").change(function() {
var nom = $("#zone-select option:selected").text(); // name of selected option
var index = zoneNom.indexOf(nom);
var new_labels = [zoneNom[index]];
var new_data1 = [zonePop[index]];
var new_data2 = [zoneSalaries[index]];
barGraph.data.labels = new_labels;
barGraph.data.datasets[0].data = new_data1;
barGraph.data.datasets[1].data = new_data2;
barGraph.update(); // update chart
});
var zoneNom = [];
var zonePop = [];
var zoneSalaries = [];
for (var i in data) {
zoneNom.push(data[i].zone_nom);
zonePop.push(data[i].zone_pop);
zoneSalaries.push(data[i].zone_salaries)
}
var chartdata = {
labels: zoneNom,
datasets: [{
label: 'Population',
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: zonePop
}, {
label: 'Salaries',
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: zoneSalaries
}]
};
var option = {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata,
options: option
});
var myBarChart;
$("#zone-select").val(zonePop[0]).trigger('change'); // select first option
},
complete: function() {}
});
}
$(document).ready(function() {
Zone();
});
<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.6.0/Chart.min.js"></script>
<select id="zone-select"></select>
<div id="chart-container">
<canvas id="mycanvas"></canvas>
</div>
I'm having trouble with percentages.
Here's the data from my database:
Jobstreet - 2 (total number of users who pick this as source of job application)
Facebook - 1 (total number of users who pick this as source of job application)
Indeed.com - 1 (total number of users who pick this as source of job application)
The code I have seems to just append the percentage sign.
Now, I'm expecting to get something like this:
Jobstreet - 50% | Facebook - 25% | Indeed.com - 25%
And if you sum them up, you'll get 100%.
I don't know how to get that. Please help me with my problem.
Here's my code:
$(document).ready(function(){
$.ajax({
url: "/public/ajax/generateChart/",
method: "GET",
success: function(data) {
var source = [];
var count = [];
for(var i in data) {
source.push(data[i].source);
count.push(data[i].number);
}
var config = {
type: 'doughnut',
data: {
datasets: [{
data: count,
backgroundColor: [
'rgba(59, 89, 152, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255,1)',
'rgba(255, 159, 64, 1)'
]
}],
labels: source
},
options: {
responsive: true,
legend: {
position: 'bottom',
},
title: {
display: false,
text: 'Chart.js Doughnut Chart'
},
animation: {
animateScale: true,
animateRotate: true
},
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var dataset = data.datasets[tooltipItem.datasetIndex];
var total = dataset.data.reduce(function(previousValue, currentValue, currentIndex, array) {
return previousValue + currentValue;
});
var currentValue = dataset.data[tooltipItem.index];
var precentage = Math.floor(((currentValue/total) * 100)+0.5);
return ": " + precentage + "%";
}
}
}
}
};
var ctx = $('#chartCanvas');
window.myDoughnut = new Chart(ctx, config);
},
error: function(data) {
console.log(data);
}
});
});
You can accomplish that using the following tooltips label callback function and a chart plugin ...
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var label = data.labels[tooltipItem.index];
var _data = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
var data = /\./.test(_data) ? _data.toFixed(2) : _data;
return label + ' - ' + data + '%';
}
}
}
ᴄʜᴀʀᴛ ᴘʟᴜɢɪɴ
plugins: [{
beforeInit: function(c) {
var data = c.data.datasets[0].data
var data_sum = data.reduce((a, b) => a + b, 0);
var each_one = 100 / data_sum;
c.data.datasets[0].data = data.map(e => e * each_one);
}
}]
add the plugin followed by your chart options
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ
$(document).ready(function() {
$.ajax({
url: "https://istack.000webhostapp.com/json/t5.json",
method: "GET",
success: function(data) {
var source = [];
var count = [];
for (var i in data) {
source.push(data[i].source);
count.push(+data[i].number);
}
var config = {
type: 'doughnut',
data: {
datasets: [{
data: count,
backgroundColor: [
'rgba(59, 89, 152, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255,1)',
'rgba(255, 159, 64, 1)'
]
}],
labels: source
},
options: {
responsive: false,
legend: {
position: 'bottom',
},
title: {
display: false,
text: 'Chart.js Doughnut Chart'
},
animation: {
animateScale: true,
animateRotate: true
},
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var label = data.labels[tooltipItem.index];
var _data = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
var data = /\./.test(_data) ? _data.toFixed(2) : _data;
return label + ' - ' + data + '%';
}
}
}
},
plugins: [{
beforeInit: function(c) {
var data = c.data.datasets[0].data
var data_sum = data.reduce((a, b) => a + b, 0);
var each_one = 100 / data_sum;
c.data.datasets[0].data = data.map(e => e * each_one);
}
}]
}
var ctx = $('#chartCanvas');
window.myDoughnut = new Chart(ctx, config);
},
error: function(data) {
console.log(data);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="chartCanvas" height="200"></canvas>
$(document).ready(function() {
$.ajax({
url: "https://istack.000webhostapp.com/json/t5.json",
method: "GET",
success: function(data) {
var source = [];
var count = [];
for (var i in data) {
source.push(data[i].source);
count.push(+data[i].number);
}
var config = {
type: 'doughnut',
data: {
datasets: [{
data: count,
backgroundColor: [
'rgba(59, 89, 152, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255,1)',
'rgba(255, 159, 64, 1)'
]
}],
labels: source
},
options: {
responsive: false,
legend: {
position: 'bottom',
},
title: {
display: false,
text: 'Chart.js Doughnut Chart'
},
animation: {
animateScale: true,
animateRotate: true
},
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var label = data.labels[tooltipItem.index];
var _data = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
var data = /\./.test(_data) ? _data.toFixed(2) : _data;
return label + ' - ' + data + '%';
}
}
}
},
plugins: [{
beforeInit: function(c) {
var data = c.data.datasets[0].data
var data_sum = data.reduce((a, b) => a + b, 0);
var each_one = 100 / data_sum;
c.data.datasets[0].data = data.map(e => e * each_one);
}
}]
}
var ctx = $('#chartCanvas');
window.myDoughnut = new Chart(ctx, config);
},
error: function(data) {
console.log(data);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="chartCanvas" height="200"></canvas>