How to put two chartjs's charts, so they both would appear? - javascript

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.

Related

Ajax won't retrieve the data from my script

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]];

Why the php code doesn't write the image?

I have a problem with an php app that sends a test result. It should load an image filled with some css, but it doesn't, it tries to load the image, but it doesn't work. It used to work. IDK what happened.
So the app should return something like this:
exemple
from this image
Original image
Is the problem in the code below?
Any help please?
foreach($charts as $id=>$chart){
?>
<script>
jQuery( document ).ready(function() {
var isSaved<?php echo $chart['name']; ?>=false;
var isImageLoad<?php echo $chart['name']; ?> = false;
var imageObj = new Image();
imageObj.src = '<?php echo get_site_url(); ?>/wp-content/themes/coaching/roata_vietii/roata2.png';
var <?php echo $chart['name']; ?> = document.getElementById("<?php echo $chart['name']; ?>");
var <?php echo $chart['name']; ?>Data = {
labels: [<?php echo $labels; ?>],
padding: {
bottom: 900
},
datasets: [{
borderWidth: 0,
data: [<?php echo ${$chart['variabila']}; ?>],
backgroundColor: [<?php echo $backgroundColor; ?> ]
}]
};
var polarAreaChart = new Chart(<?php echo $chart['name']; ?>, {
type: 'polarArea',
data: <?php echo $chart['name']; ?>Data,
responsive:false,
options: {
events: [],
layout: {
padding: {
left:70,
right:70,
//top:10,
//bottom:10
},
},
legend: {
display:false,
/* labels: {
padding:20,
boxWidth:20,
fontSize:15
},*/
},
scale: {
ticks: {
min: 0,
max: 10,
display:false,
},
},
hover: {
animationDuration: 0
},
animation: {
duration: 0,
onComplete: function() {
var chartInstance = this.chart;
var ctx = chartInstance.ctx;
var datasets = this.data.datasets;
imageObj.onload = function() {
if(isSaved<?php echo $chart['name']; ?> == false){
ctx.drawImage(imageObj, 0, 0);
/* ctx.font = "bolder 15px Arial";
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
ctx.fillStyle = "grey";
datasets.forEach(function(dataset, i) {
var meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function(bar, index) {
var myangl=((bar._model.startAngle)+(bar._model.endAngle))/2;
// var xpoint= (parseFloat(bar._model.outerRadius)+20)*(Math.cos(myangl)) + (bar._model.x);
// var ypoint= (parseFloat(bar._model.outerRadius)+20)*(Math.sin(myangl)) + (bar._model.y);
var xpoint= (parseFloat(370)+20)*(Math.cos(myangl)) + (bar._model.x);
var ypoint= (parseFloat(370)+20)*(Math.sin(myangl)) + (bar._model.y);
ctx.fillText(bar._model.label,xpoint ,ypoint);
});
});*/
isSaved<?php echo $chart['name']; ?> = true;
jQuery.ajax({
url: '<?php echo get_site_url(); ?>/wp-content/themes/coaching/roata_vietii/roataVietii-saver.php',
type: 'POST',
data: {
"image" : <?php echo $chart['name']; ?>.toDataURL("image/<?php echo $chart['extension']; ?>"),
"name" : "<?php echo $chart['name_of_file']; ?>" + ".<?php echo $chart['extension']; ?>",
"save_location" : "<?php echo $chart['save_location']; ?>" ,
},
success: function ()
{
<?php /*if($id !== 1 ){ ?>
//if the image is saved, resize the canvas to 100%, for the user
setTimeout(function () {
var tmpCC = document.getElementById("chart-container<?php echo $chart['name']; ?>");
tmpCC.style.backgroundImage = 'url("<?php echo get_site_url(); ?>/wp-content/themes/coaching/roata_vietii/images/<?php echo $chart['name_of_file'].".".$chart['extension'];?>")';
tmpCC.style.width = "100%";
tmpCC.style.height = tmpCC.offsetWidth+"px";
},500);
<?php } */ ?>
},
});
}
}
}
}
}
});
});
</script>

Reading MySQL data into highstocks

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?

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>

Passing PHP-Variables to Jquery

i want to load some data from an sql-table and use them with jquery to color a map.
I picked up the data with PHP:
<?php
include 'connect.php';
session_start();
$userid = $_SESSION['userid'];
$sql = "
SELECT landstatus.shortland
FROM landstatus
WHERE users_id='1'
AND status ='wanttovisit'
";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["shortland"]. "<br>";
}
}
$conn->close();
?>
Now i want to use shortland for the static value 'ca' in jquery:
<script>
jQuery(document).ready(function () {
jQuery('#vmap').vectorMap({
map: 'world_en',
backgroundColor: '#333333',
color: '#FFFFFF',
hoverOpacity: 0.7,
selectedColor: '#727272',
enableZoom: true,
colors:{
'ca' : '#4E7387',
},
series: {
regions:
[{
attribute: 'fill'
}]
},
onRegionClick: function (element, code, region) {
$(".info-box-region").append(region);
$(".info-box").show();
$("input[name=region]").val(region);
$('input[name=code]').val(code);
}
});
});
</script>
At the end colors would be filled with all shortlands from the database - each shortland has the same hex-code.
Thx for helping me.
Place all shortland values in an array and loop through it to create the ca entries
$result = $conn->query($sql);
$shortlands = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$shortlands[] = $row["shortland"];
}
}
Then loop over the values. e.g.
colors:{
<?php
foreach ($shortlands as $val) {
echo "'{$val}': '#4E7387',\n";
}
?>
},
You can "pass" anything PHP knows into JavaScript variables simply by echoing them into JavaScript code in your template:
<script>
var myJavaScriptVar = <?php echo $myPhpVar ?>
</script>
Just do this:
<script>
jQuery(document).ready(function () {
jQuery('#vmap').vectorMap({
map: 'world_en',
backgroundColor: '#333333',
color: '#FFFFFF',
hoverOpacity: 0.7,
selectedColor: '#727272',
enableZoom: true,
colors:{
'ca' : '<?php echo $row["shortland"] ;?>',
},
series: {
regions:
[{
attribute: 'fill'
}]
},
onRegionClick: function (element, code, region) {
$(".info-box-region").append(region);
$(".info-box").show();
$("input[name=region]").val(region);
$('input[name=code]').val(code);
}
});
});
</script>

Categories

Resources