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>
Related
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"}]
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.
I have made the code to draw a graph using the data obtained from a query in the database.
HTML:
<div>
<canvas id="mycanvas" height="150"></canvas>
</div>
PHP
$result = $mysqli->query("SELECT COUNT(social_id) as total, DATE_FORMAT(login_at, '%d-%m') as datee
FROM social_users_connections
WHERE login_at < DATE_ADD(NOW(), INTERVAL +1 MONTH)
AND client_id = $clientID
GROUP BY datee
ORDER BY login_at");
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//free memory associated with result
$result->close();
//close connection
$mysqli->close();
// print_r($data);
//now print the data
print json_encode($data);
AJAX:
$(document).ready(function () {
Chart.defaults.scale.ticks.beginAtZero = true;
$.ajax({
url: "view/ajax/php/data.php",
method: "GET",
success: function (data) {
console.log(data);
var player = [];
var score = [];
for (var i in data) {
player.push(data[i].total);
score.push(data[i].datee);
}
var chartdata = {
labels: score,
datasets: [{
label: 'Client Connections',
backgroundColor: 'rgba(0, 158, 251, 0)',
borderColor: 'rgba(0, 158, 251, 1)',
hoverBackgroundColor: 'rgba(0, 158, 251, 0)',
hoverBorderColor: 'rgba(0, 158, 251, 1)',
data: player
}]
};
var chartOptions = {
legend: {
display: true,
position: 'top',
labels: {
boxWidth: 80,
fontColor: 'black'
}
},
scales: {
xAxes: [{
gridLines: {
display: false,
color: "black"
},
scaleLabel: {
display: true,
labelString: "Fecha"
}
}],
yAxes: [{
gridLines: {
color: "black",
borderDash: [2, 5]
},
scaleLabel: {
display: true,
labelString: "Número de conexiones"
},
ticks: {
stepSize: 5
}
}]
}
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'line',
data: chartdata,
options: chartOptions
});
},
error: function (data) {
console.log(data);
}
});
});
Result:
What I need to do is add 2 input for the user to choose two dates and show a certain range. I tried to pass the input values through ajax to the PHP script to change the query but without success.
I tried this too:
HTML:
<input class="text-center" name="filter_date_from" type="date" id="filter_date_from" placeholder="fecha">
<input class="text-center" name="filter_date_to" type="date" id="filter_date_to" placeholder="fecha">
<button class="btn btn-primary" onclick="filterGraph()">Filtrar</button>
AJAX:
<script>
function filterGraph() {
var datefrom = document.getElementById('filter_date_from').value;
var dateto = document.getElementById('filter_date_to').value;
Chart.defaults.scale.ticks.beginAtZero = true;
$.ajax({
url: "view/ajax/php/data_filter.php",
method: "GET",
data: {
datefrom : datefrom,
dateto : dateto
},
success: function (data) {
console.log(data);
var player = [];
var score = [];
for (var i in data) {
player.push(data[i].total);
score.push(data[i].datee);
}
var chartdata = {
labels: score,
datasets: [{
label: 'Client Connections',
backgroundColor: 'rgba(0, 158, 251, 0)',
borderColor: 'rgba(0, 158, 251, 1)',
hoverBackgroundColor: 'rgba(0, 158, 251, 0)',
hoverBorderColor: 'rgba(0, 158, 251, 1)',
data: player
}]
};
var chartOptions = {
legend: {
display: true,
position: 'top',
labels: {
boxWidth: 80,
fontColor: 'black'
}
},
scales: {
xAxes: [{
gridLines: {
display: false,
color: "black"
},
scaleLabel: {
display: true,
labelString: "Fecha"
}
}],
yAxes: [{
gridLines: {
color: "black",
borderDash: [2, 5]
},
scaleLabel: {
display: true,
labelString: "Número de conexiones"
},
ticks: {
stepSize: 5
}
}]
}
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'line',
data: chartdata,
options: chartOptions
});
},
error: function (data) {
console.log(data);
}
});
}
</script>
PHP:
$date_from = $_POST['datefrom'];
$date_to = $_POST['dateto'];
$from = date('d-m', $date_from);
$to = date('d-m', $date_to);
$result = $mysqli->query("SELECT COUNT(social_id) as total, DATE_FORMAT(login_at, '%d-%m') as datee
FROM social_users_connections
WHERE DATE_FORMAT(login_at, '%d-%m') BETWEEN '$from' AND '$to'
AND client_id = '$clientID'
GROUP BY datee
ORDER BY login_at");
echo $result;
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//free memory associated with result
$result->close();
//close connection
$mysqli->close();
// print_r($data);
//now print the data
print json_encode($data)
;
But i have this error y at console:
GET http://35.177.140.48/view/ajax/php/data_filter.php?datefrom=2018-04-01&dateto=2018-04-26 500 (Internal Server Error)
I hope someone can guide me on how to do it.
Thanks in advance.
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.