Chart.js jQuery dropdown selected values - php

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>

Related

Grouped Bar Chart from mySQL database using ChartJS and PHP

index.php - fetches data from mySQL database
<?php
header('Content-Type: application/json');
$conn = mysqli_connect('localhost', 'root', '', 'registration');
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$query = sprintf("SELECT ratingid, variety, quality FROM chartdata ORDER BY ratingid");
$result = mysqli_query($conn, $query);
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
mysqli_close($conn);
print json_encode($data);
?>
app.js
$(document).ready(function(){
$.ajax({
url: "http://localhost/mychart4/index.php",
method: "GET",
success: function(data) {
console.log(data);
var rating = [];
var variety = [];
var quality = [];
for(var i in data) {
rating.push(data[i].ratingid);
variety.push(data[i].variety);
quality.push(data[i]).quality);
}
var chartdata = {
labels: rating,
datasets: [
{
label: 'Red',
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: variety
},
{
label: 'Blue',
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: quality
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata,
options: {
barValueSpacing: 20,
title: {
display: true,
text: 'Variety',
fontSize: 20
},
scales: {
xAxes: [{
scaleLabel: {
display: true,
labelString: 'Rating options'
}
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Amount'
},
ticks: {
beginAtZero: true
}
}]
}
}
});
},
error: function(data) {
console.log(data);
}
});
});
bargaph.html
<!DOCTYPE html>
<html>
<head>
<title>ChartJS - BarGraph</title>
<style type="text/css">
#chart-container {
width: 640px;
height: auto;
}
</style>
</head>
<body>
<div id="chart-container">
<canvas id="mycanvas"></canvas>
</div>
<!-- javascript -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/Chart.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>
I'm trying to render a grouped bar chart using ChartJS with values from several columns(variety,quality) in my mySQL database. However, the browser does not display anything when I open the HTML file. I'm not sure what the issue might be since the bar chart rendered correctly when I tried it with one column(variety).
This is the output when I print out the JSON array formed from the data:
[{"ratingid":"1","variety":"8","quality":"1"},{"ratingid":"2","variety":"1","quality":"9"},{"ratingid":"3","variety":"1","quality":"0"},{"ratingid":"4","variety":"11","quality":"11"},{"ratingid":"5","variety":"1","quality":"1"}]
There's a very small mistake in the code that needs to be removed.
Current Code:
quality.push(data[i]).quality);
Correction:
quality.push(data[i].quality);
There's just an additional ')' that needs to be removed and it worked...
Bar Chart
Complete working code as below;
<!-- index.php -->
<?php
header('Content-Type: application/json');
$conn = mysqli_connect('localhost', 'root', '', 'registration');
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$query = sprintf("SELECT ratingid, variety, quality FROM chartdata ORDER BY
ratingid");
$result = mysqli_query($conn, $query);
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
mysqli_close($conn);
print json_encode($data);
//-- app.js
$(document).ready(function () {
$.ajax({
url: "http://localhost/test/barChart/index.php",
method: "GET",
success: function (data) {
console.log(data);
var rating = [];
var variety = [];
var quality = [];
for (var i in data) {
rating.push(data[i].ratingid);
variety.push(data[i].variety);
quality.push(data[i].quality);
}
var chartdata = {
labels: rating,
datasets: [{
label: 'Red',
backgroundColor: 'rgb(255, 0, 0)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: variety
},
{
label: 'Blue',
backgroundColor: 'rgb(0, 0, 255)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: quality
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata,
options: {
barValueSpacing: 20,
title: {
display: true,
text: 'Variety',
fontSize: 20
},
scales: {
xAxes: [{
scaleLabel: {
display: true,
labelString: 'Rating options'
}
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Amount'
},
ticks: {
beginAtZero: true
}
}]
}
}
});
},
error: function (data) {
console.log(data);
}
});
});
<!-- bargraph.html -->
<!DOCTYPE html>
<html>
<head>
<title>ChartJS - BarGraph</title>
<style type="text/css">
#chart-container {
width: 640px;
height: auto;
}
</style>
</head>
<body>
<div id="chart-container">
<canvas id="mycanvas"></canvas>
</div>
<!-- javascript -->
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>

Can't pull oci array with ajax for use with ChartJs

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?

Error using chartJs on laravel project

I am trying to use chartJs to draw a bar chart on my laravel project but I have been getting this error -
"Failed to create chart: can't acquire context from the given item".
I have tried debugging and I think everything looks okay.
This is my JS file
$(document).ready(function () {
$.ajax({
url: "{{url('properties','totalTaxPaidByLga')}}",
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);
}
});
});
This is my blade file
<div id="chart-container">
<canvas id="mycanvas"> </canvas>
<p>Hi</p>
</div>
This is my controller
public function totalTaxPaidByLga(){
$query = DB::select("select SUM(a.settlement_amount) as totalTaxPaid, d.local_name from settlements as a, assessments as b,
property_details as c, locals as d
where a.assessment_ref = b.assessment_ref and
b.property_id = c.id and
c.lga_id = d.local_id
GROUP BY d.local_id");
foreach ($query as $row) {
$data[] = $row;
}
print json_encode($data);
}

How to get percentage from data collected in ChartJS?

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>

How to make a graph using PHP from oracle

I want to create a graph that the data are from oracle by using php.
I did not found example that use oracle as a database. Mostly are from mysql.
The data is like this
I have made this code but it's not working.
its show like this
data.php
<?php
header('Content-Type: application/json');
$conn = oci_connect('***', '***', '127.0.0.1/orcl');
$graph=sprintf("SELECT count(pm.packagename) as quantity,pm.packagename
FROM packagemenu pm
INNER JOIN orderdetail od ON od.packageid=pm.packageid
inner join orders o on o.orderid = od.orderid
group by pm.packagename");
$parse=oci_parse($conn,$graph);
oci_execute($parse);
$data=array();
while($row1 = oci_fetch_array($parse)){
$data[]=$row1;
}
print json_encode($data);
?>
bargraph.html
<!DOCTYPE html>
<html>
<head>
<title>ChartJS - BarGraph</title>
<style type="text/css">
#chart-container {
width: 640px;
height: auto;
}
</style>
</head>
<body>
<div id="chart-container">
<canvas id="mycanvas"></canvas>
</div>
<!-- javascript -->
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="js/Chart.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
apps.js
$(document).ready(function(){
$.ajax({
url: "http://localhost/psm/admin/data.php",
method: "GET",
success: function(data) {
console.log(data);
var packagename = [];
var quantity = [];
for(var i in data) {
packagename.push("Packagename " + data[i].packagename);
quantity.push(data[i].quantity);
}
var chartdata = {
labels: packagename,
datasets : [
{
label: 'Package Name',
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: quantity
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});
Since the data is this:
[{"0":"8","QUANTITY":"8","1":"Set A","PACKAGENAME":"Set A"},{"0":"5","QUANTITY":"5","1":"Set B","PACKAGENAME":"Set B"}]
You have a case sensitivity problem, which makes the array var packagename and quantity empty/undifined.
You need to change:
for(var i in data) {
packagename.push("Packagename " + data[i].packagename);
quantity.push(data[i].quantity);
}
... to ...
for(var i in data) {
packagename.push("Packagename " + data[i].PACKAGENAME);
quantity.push(data[i].QUANTITY);
}
I am not familiar with Chart.js but fixing this so that you are not trying to graph undefined variables is a first step.

Categories