Hello so i try to retrieve data from a .php with Ajax to make a Doughnut chart with Chart.JS
Here is what i have (value 1, 2, 3, 4 in the legend order) :
This is my Chart.JS Script :
// Set new defawult font family and font color to mimic Bootstrap's default styling
Chart.defaults.global.defaultFontFamily = 'Nunito', '-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif';
Chart.defaults.global.defaultFontColor = '#858796';
$.ajax({
url:"./inc/pie_chart.inc.php",
method:"GET",
success:function(data) {
console.log(data);
var appelsnum =[1];
var mailsnum =[2];
var anomaliesnum =[3];
var decnum =[4];
// Pie Chart Example
var ctx = document.getElementById("myPieChart");
var myPieChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ["Appels", "Mails", "Anomalies", "DEC"],
datasets: [{
data: [appelsnum, mailsnum, anomaliesnum, decnum],
backgroundColor: ['#36b9cc', '#1cc88a', '#e74a3b', '#f6c23e'],
hoverBackgroundColor: ['#2c9faf', '#17a673', '#a3281c', '#dbac32'],
hoverBorderColor: "rgba(234, 236, 244, 1)",
}],
},
options: {
maintainAspectRatio: false,
tooltips: {
backgroundColor: "rgb(255,255,255)",
bodyFontColor: "#858796",
borderColor: '#dddfeb',
borderWidth: 1,
xPadding: 15,
yPadding: 15,
displayColors: false,
caretPadding: 10,
},
legend: {
display: false
},
cutoutPercentage: 80,
},
});
},
});
And this is my "pie_chart.inc.php" file (the one who Ajax is retrieving) :
<?php
header('Content-Type:text/plain');
require_once('./loggedin.inc.php');
require_once('./db.inc.php');
require_once('./settings.inc.php');
$sql="SELECT SUM(appels_res) AS totalsumappelsmonth FROM resultats ORDER BY id DESC LIMIT 14";
$result = mysqli_query($conn, $sql);
$appelsnum = mysqli_fetch_assoc($result);
$appelsnum = $appelsnum['totalsumappelsmonth'];
$sql="SELECT SUM(mails_res) AS totalsummailsmonth FROM resultats ORDER BY id DESC LIMIT 14";
$result = mysqli_query($conn, $sql);
$mailsnum = mysqli_fetch_assoc($result);
$mailsnum = $mailsnum['totalsummailsmonth'];
$sql="SELECT SUM(anomalies_res) AS totalsumanomaliesmonth FROM resultats ORDER BY id DESC LIMIT 14";
$result = mysqli_query($conn, $sql);
$anomaliesnum = mysqli_fetch_assoc($result);
$anomaliesnum = $anomaliesnum['totalsumanomaliesmonth'];
$sql="SELECT SUM(dec_res) AS totalsumdecmonth FROM resultats ORDER BY id DESC LIMIT 14";
$result = mysqli_query($conn, $sql);
$decnum = mysqli_fetch_assoc($result);
$decnum = $decnum['totalsumdecmonth'];
$data=array();
$data[0]=$appelsnum;
$data[1]=$mailsnum;
$data[2]=$anomaliesnum;
$data[3]=$decnum;
$result->close();
$conn->close();
print json_encode($data);
?>
When i'm visiting this page, there is what it's returning to me :
Theses are the good values that must be on the Charts.
However, i'm getting 1, 2, 3, 4.
Do you know how to fix this?
Thanks for reading :) Greetings.
You are getting 1,2,3,4 because they are hardcoded. Try changing
var appelsnum =[1];
var mailsnum =[2];
var anomaliesnum =[3];
var decnum =[4];
to
var appelsnum =[data[0]];
var mailsnum =[data[1]];
var anomaliesnum =[data[2]];
var decnum =[data[3]];
Related
I am trying to input my Controller variable in ChartJS Javascript file to Dynamically create charts in ChartJS
Expression Expected at "<?"
Controller.php
public function index(Request $request)
{
#$result= DB::select("SELECT * FROM table WHERE user_id =?", [$user_id]);
$result_arr = json_decode(json_encode($result), true);
$label_array = array();
foreach($result_arr as $d)
{
$label_array[]=$d['label_element'];
}
$data_array = array();
foreach($result_arr as $d)
{
$data_array[]=$d['data_element'];
}
return view('home', ['labels'=>$label_array, 'data'=>$data_array]);
}
chart-pie-demo.js:
// Pie Chart Example
var ctx = document.getElementById("myPieChart");
var myPieChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: <?php echo json_encode($labels); ?>, // Error Line
datasets: [{
data: <?php echo json_encode($data); ?>, // Error Line
backgroundColor: ['#4e73df', '#1cc88a', '#36b9cc'],
hoverBackgroundColor: ['#2e59d9', '#17a673', '#2c9faf'],
hoverBorderColor: "rgba(234, 236, 244, 1)",
}],
},
I have created a MySQL database and I am running xampp locally.
Here is my data.php:
<?php
//setting header to json
header('Content-Type: application/json');
//database
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'products');
//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 date, url, price FROM table1");
//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);
The output file generates the date, price and url
When I then take a look at my barchart.html, I am trying to introduce a onclick link to url when user clicks on each bar.
$(document).ready(function(){
$.ajax({
url: "http://192.168.64.2/fs/data.php",
method: "GET",
success: function(data) {
console.log(data);
var date = [];
var price = [];
for(var i in data) {
date.push("" + data[i].date);
price.push(data[i].price);
}
var chartdata = {
labels: date,
datasets : [
{
label: '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 ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});
This is the bar chart which is generated;
When I hover over the bar chart, the date and price show up, however on click, I want to send user to url, as pulled from the table1 in data.php
I making a page for teachers where they can see a score their students' score and for that there are charts to show the amount of students got correct on each question. I tried to just put two charts, but it only shows one of the charts and the other chart has been as a blank. I thought the problem if happening because both charts has the same name, but after I changed one of the names of the chart, but it still only shows one of the charts. Here this is my php/html/js code:
<?php
if (isset($_GET['question'])) {
$con = mysqli_connect("localhost", "root", "", "testing");
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
$sql = "SELECT * FROM `chapter 7 vocabulary test` WHERE `score".$_GET["question"]."`='1'";
$result = mysqli_query($con, $sql);
$full = mysqli_num_rows($result);
mysqli_free_result($result);
$sql = "SELECT * FROM `chapter 7 vocabulary test` WHERE `score".$_GET["question"]."`='0'";
$result = mysqli_query($con, $sql);
$none = mysqli_num_rows($result);
mysqli_free_result($result);
?>
<script src="jquery-3.3.1.min.js"></script>
<script src="Chart.js"></script>
<div id="canvas"><canvas id="questioncan1" style="height: 25vh; width: 25vh;"></canvas></div>
<script type="text/javascript">
let myChart = document.getElementById('questioncan1').getContext("2d");
Chart.defaults.global.defaultFontFamily = "Arial";
Chart.defaults.defaultFontSize = 18;
Chart.defaults.global.defaultFontColor = "black";
let questioncan1 = new Chart(myChart, {
type: "doughnut",
data: {
labels: [
"Full Credit",
"No Credit"
],
datasets: [
{
data: [
5,
15
],
backgroundColor: [
"#11FF00",
"#F7301E"
],
borderWidth: 0
}
]
},
options: {
scaleShowLabels: false,
responsive: false,
legend: {
display: false
}
}
});
</script>
<br><br>
<table>
<tr>
<th>Name</th>
<th>Status</th>
</tr>
<?php
$sql = "SELECT * FROM `chapter 7 vocabulary test`";
$result = $con->query($sql);
while ($row = $result->fetch_assoc()) {
$sql2 = "SELECT * FROM `users` WHERE `snumber`='".$row["snumber"]."'";
$result2 = $con->query($sql2);
while ($row2 = $result2->fetch_assoc()) {
echo "<tr><td>".$row2['name']."</td><td>".$row["score".$_GET['question']]."</td></tr>";
}
}
?>
</table>
<script src="jquery-3.3.1.min.js"></script>
<div id="canvas"><canvas id="questioncan" style="height: 25vh; width: 25vh;"></canvas></div>
<script type="text/javascript">
let myChart = document.getElementById('questioncan').getContext("2d");
Chart.defaults.global.defaultFontFamily = "Arial";
Chart.defaults.defaultFontSize = 18;
Chart.defaults.global.defaultFontColor = "black";
let questioncan = new Chart(myChart, {
type: "doughnut",
data: {
labels: [
"Full Credit",
"No Credit"
],
datasets: [
{
data: [
<?php echo $full; ?>,
<?php echo $none; ?>
],
backgroundColor: [
"#11FF00",
"#F7301E"
],
borderWidth: 0
}
]
},
options: {
scaleShowLabels: false,
responsive: false,
legend: {
display: false
}
}
});
</script>
<br><br>
<table>
<tr>
<th>Name</th>
<th>Status</th>
</tr>
<?php
$sql = "SELECT * FROM `chapter 7 vocabulary test`";
$result = $con->query($sql);
while ($row = $result->fetch_assoc()) {
$sql2 = "SELECT * FROM `users` WHERE `snumber`='".$row["snumber"]."'";
$result2 = $con->query($sql2);
while ($row2 = $result2->fetch_assoc()) {
echo "<tr><td>".$row2['name']."</td><td>".$row["score".$_GET['question']]."</td></tr>";
}
}
?>
</table>
<?php
}
?>
You're declaring the variable "myChart" twice globally, rather than in separate functions, so it's only outputting one of them.
Set the second chart to:
let myChart2 = document.getElementById('questioncan2').getContext("2d");
https://jsfiddle.net/xea4qr8k/12/
Also recommend changing your div IDs to be unique, and remove the second script src for jQuery.
So this is the first time i have really worked with high charts i have some data reading into high charts from my MySQL database, but the next step is to try and set up a high stocks chart. Whenever i try and use the same method as i did with high charts the chart doesn't work? This is what i want to aim for - StockChartDemo
PHP Code:
$conn = new mysqli($servername, $username, $password, $dbName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "(SELECT date AS time ,IFNULL(RH,'null')AS humidity
FROM test ORDER BY date DESC LIMIT 20) ORDER BY time ASC";
$result = $conn->query($sql);
if ($result->num_rows>0){
$count =0;
echo '[';
while($row=$result->fetch_assoc()){
echo '['.$row["time"].',' .$row["humidity"].']';
$count++;
if ($count<"20"){
echo ',';
}
}
echo ']';
}else{
echo "[[],[]]";
}
$conn->close();
?>
html & jQuery:
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="highstock.js"></script>
</head>
<script type="text/javascript">
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var options = {
chart: {
renderTo: 'tempcontainer',
alignTicks: false,
height:320,
},
rangeSelector: {
selected: 1
},
title: {
text: 'Relative humidity'
},
series: [{
type: 'column',
name: 'Humidity',
data: json,
dataGrouping: {
units: [[
'month', // unit name
[1] // allowed multiples
], [
'week',
[1, 2, 3, 4, 6]
]]
}
}]
}
$.getJSON("stockdata.php", function(json) { /*Get the array data in data.php using jquery getJSON function*/
options.series[0].data = json; /*assign the array variable to chart data object*/
chart = new Highcharts.stockChart(options); /*create a new chart*/
});
function refreshChart(){ /*function is called every set interval to refresh(recreate the chart) with the new data from data.php*/
setInterval(function(){
$.getJSON("stockdata.php", function(json) {
options.series[0].data = json;
chart = new Highcharts.stockChart(options);
});
},60000);
}
});
</script>
<div id="tempcontainer"></div>
Presuming your query is returning the correct data you want. (I'm not up for mocking it out to test your query)
You should switch out the following code, and all that in-between.
if ($result->num_rows>0){
//snip
}
To use json_encode() instead.
$series = [];
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$series[] = [
$row["time"],
$row["humidity"]
];
}
}
header('Content-Type: application/json');
exit(json_encode($series));
How to display the sum in this graph. I have the same year in my database (2012) How can i add those 2 data? And display automatically in graph? This is the codes of my sample:
<?php
$connect = mysqli_connect("localhost", "root", "", "testing");
$query = "SELECT * FROM account";
$result = mysqli_query($connect, $query);
$chart_data = '';
while($row = mysqli_fetch_array($result)) {
$chart_data .= "{ year:'".$row["year"]."', profit:".$row["profit"].",
purchase:".$row["purchase"].", sale:".$row["sale"]."}, ";
}
$chart_data = substr($chart_data, 0, -2);
?>
<script type="text/javascript">
config = {
data: [<?php echo $chart_data; ?>],
xkey: 'year',
ykeys: ['profit', 'purchase', 'sale'],
labels: ['Profit', 'Purchase', 'Sale'],
fillOpacity: 0.6,
hideHover: 'auto',
behaveLikeLine: true,
resize: true,
pointFillColors: ['#ffffff'],
pointStrokeColors: ['black'],
lineColors: ['gray','red']
};
</script>