Helloi have a problem with chart.js, php and informix database.
first i test the script with easy mysql database and they works good.
but when im using informix database with pdo he show me on chart label undefined.
=> my data.php (for connection to database) :
<?php
header('Content-Type: application/json');
$db=new pdo("informix:host=uccxpub;service=1504;database=db_cra;server=uccxpub_uccx;protocol=onsoctcp;EnableScrollabelCursors=1;client_local=en_US.UTF8;db_locale=en_US.UTF8","uccxwallboard","cisco2016"
) or die("Impossible de se connecter !!!");
$sql0 = sprintf("SELECT * FROM RtCSQsSummary where CSQName = 'BMCE BANK'");
/*$stmt = $db->prepare($sql0);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
*/
$result = $db->query($sql0);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//now print the data
print json_encode($data);
?>
=> the output of data.php :
enter image description here
=> my bargraph.js :
$(document).ready(function(){
$.ajax({
url: "../data.php",
method: "GET",
success: function(data) {
console.log(data);
var startdatetime = [];
var loggedInAgents = [];
for(var i in data) {
startdatetime.push("startdatetime " + data[i].startdatetime);
loggedInAgents.push(data[i].loggedInAgents);
}
var chartdata {
labels: startdatetime,
datasets : [
{
label: 'loggedInAgents',
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: loggedInAgents,
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});
=> the output :
enter image description here
=> my index.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/bargraph.js"></script>
</body>
</html>
!! the bar graph not show me callshandled undefinded ..
test with mysql database :
=> data.php :
<?php
//setting header to json
header('Content-Type: application/json');
//database
define('DB_HOST', '127.0.0.1');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'root123');
define('DB_NAME', 'mydb');
//get connection
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}
//query to get data from the table
$query = sprintf("SELECT playerid, score FROM score ORDER BY playerid");
//execute query
$result = $mysqli->query($query);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//free memory associated with result
$result->close();
//close connection
$mysqli->close();
//now print the data
print json_encode($data);
=>bargraph.js :
$(document).ready(function(){
$.ajax({
url: "http://localhost/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);
}
});
});
=> index.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/bargraph.js"></script>
</body>
</html>
hes work so fine.
I ran your code (with some minor fixes) on my Linux box. I can display the bar graph with some simple test data from an Informix database:
html page:
informix#irk:/var/www/html# cat test.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="http://code.jquery.com/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<script src="http://irk/b.js"></script>
</body>
</html>
informix#irk:/var/www/html#
javascript:
informix#irk:/var/www/html# cat b.js
$(document).ready(function(){
$.ajax({
url: "http://irk/data.php",
method: "GET",
success: function(data) {
var obj=JSON.parse(data);
data=obj;
var startdatetime = [];
var loggedInAgents = [];
for(var i in data) {
startdatetime.push( data[i].STARTDATETIME);
loggedInAgents.push(data[i].LOGGEDINAGENTS);
}
var chartdata = {
labels: startdatetime,
datasets : [
{
label: 'loggedInAgents',
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: loggedInAgents
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});
informix#irk:/var/www/html#
php script getting the data from Informix:
informix#irk:/var/www/html# cat data.php
<?php
$db=new pdo("informix:database=enusutf8;server=irk1210;CLIENT_LOCALE=en_US.UTF8;DB_LOCALE=en_US.UTF8","informix","testpwd") or die("Impossible de se connecter !!!");
$sql0 = sprintf("SELECT * FROM RtCSQsSummary where CSQName = 'BMCE BANK'");
$result = $db->query($sql0);
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
print json_encode($data);
?>
informix#irk:/var/www/html#
In addition to the uppercase/lowercase mentioned before, the JSON data the JS function gets
has to be parse before it can be used. Otherwise you will get "undefied" values in the 'for(var i in data)' loop, no matter what case you used.
Related
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>
I am having difficulty figuring out how to use Highcharts to get new(live) data from a database.
I have tested the example here and it works great.
I get new data written to the database every 1min. The problem is I can only make it grab the newly inserted data from the database and update the chart every 1min, using the newly inserted data as the new data point. I can't get it to show historical data from the database.
Here is an example of what I'm trying to do.
Here is the code I´m using at the moment.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
var chart;
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'area',
zoomType: 'x'
},
title: {
},
xAxis: {
type: 'datetime'
},
yAxis: {
},
series: [{
name: 'Download',
data: []
}, {
name: 'Upload',
data: []
}]
};
$.getJSON('data.php', function(json) {
data1 = [];
data2 = [];
$.each(json, function(key,value) {
data1.push([value[0], value[1]]);
data2.push([value[0], value[2]]);
});
options.series[0].data = data1;
options.series[1].data = data2;
chart = new Highcharts.stockChart(options);
});
});
</script>
<body>
<div id="container" style="min-width: 400px; height: 800px; margin: 0 auto"></div>
</body>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/data.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
And here is the code for data.php.
<?php
$dbhost = 'localhost';
$dbname = 'highchart';
$dbuser = '*******';
$dbpass = '*******';
try{
$dbcon = new PDO("mysql:host={$dbhost};dbname={$dbname}",$dbuser,$dbpass);
$dbcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $ex){
die($ex->getMessage());
}
$stmt=$dbcon->prepare("SELECT * FROM trafico");
$stmt->execute();
$json = [];
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
$json[]= [strtotime($time_1m)*1000, (int)$Tx, (int)$Rx];
}
echo json_encode($json);
?>
This is the output I get from data.php.
[[1521071984000,1255,91],[1521072190000,1212,92],[1521072241000,1220,93],[ ... ]]
This is the graph I get
Basically I don't know to how to make the code (this graph) above to update dynamically every 1min with new data points.
Problem solved.
This is the code I added:
events: {
load: function requestData() {
$.ajax({
url: 'live.php',
success: function(points) {
var series = chart.series,
shift;
$.each(series, function(i, s) {
shift = s.data.length > 1;
s.addPoint(points[i], true, true);
});
setTimeout(requestData, 1000);
chart.redraw();
},
cache: false
});
}
}
Now I have historical data from my DB and it adds new data point every time there's a new entry in de DB without the need to refresh the page.
Here is is my live.php code:
<?Php
header("Content-type: text/json");
$dbhost = 'localhost';
$dbname = 'highchart';
$dbuser = '*******';
$dbpass = '*******';
try{
$dbcon = new PDO("mysql:host={$dbhost};dbname={$dbname}",$dbuser,$dbpass);
$dbcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $ex){
die($ex->getMessage());
}
$stmt=$dbcon->prepare("SELECT * FROM trafico");
$stmt->execute();
$json = [];
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
}
$json[]= [strtotime($time_1m)*1000, (int)$Tx];
$json[]= [strtotime($time_1m)*1000, (int)$Rx];
echo json_encode($json);
?>
This is the output from live.php:
[[1522869181000,872],[1522869181000,54]]
and this is how the code looks now
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
var chart;
$(document).ready(function() {
Highcharts.setOptions({
time: {
timezoneOffset: 3 * 60
}
});
var options = {
chart: {
renderTo: 'container',
type: 'area',
zoomType: 'x',
events: {
load: function requestData() {
$.ajax({
url: 'live.php',
success: function(points) {
var series = chart.series,
shift;
$.each(series, function(i, s) {
shift = s.data.length > 1;
s.addPoint(points[i], true, true);
});
setTimeout(requestData, 1000);
chart.redraw();
},
cache: false
});
}
}
},
title: {
},
xAxis: {
type: 'datetime'
},
yAxis: {
},
series: [{
name: 'Download',
data: []
}, {
name: 'Upload',
data: []
}]
};
$.getJSON('data.php', function(json) {
data1 = [];
data2 = [];
$.each(json, function(key,value) {
data1.push([value[0], value[1]]);
data2.push([value[0], value[2]]);
});
options.series[0].data = data1;
options.series[1].data = data2;
chart = new Highcharts.stockChart(options);
});
});
</script>
<body>
<div id="container" style="min-width: 400px; height: 800px; margin: 0 auto"></div>
</body>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/data.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
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);
}
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 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.