PHP not showing within the data part of a chart.js - javascript

I have managed to get both PHP and JavaScript code working on the same page. In the top of the page on the left you can see that my figures from my php tables are being pulled out correctly however, the moment I go to paste the php code inside of where the table 'data' needs to be kept it doesn't work even though surrounded in php tags.
<?php
$conn = mysqli_connect("localhost", "x", "y", "z");
$query = "SELECT * FROM `checkPointMod`";
$result = $conn -> query($query);
while($row = $result -> fetch_assoc())
{
echo $row['mod1']."<br>";
echo $row['mod2']."<br>";
echo $row['mod3']."<br>";
echo $row['mod4']."<br>";
echo $row['mod5']."<br>";
echo $row['mod6']."<br>";
}
$conn -> close();
?>
<!DOCTYPE html>
<html lang="en-GB">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
</head>
<body style="background-color: lightgrey;">
<div class="col-md-4 text-center">Third of Page - Middle section with progress bar
<canvas id="myChart" width="400" height="400"></canvas>
</div>
<script type="text/javascript">
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [<?php echo $row['mod1']?>, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
</script>
</html>
Update: - I've gone to inspect element to see what the output is and it's seen here, I also placed mod2 in to see if 6 would appear...

I missed that $row only exists inside that while loop.
Replace your while loop with this:
$rows = [];
while ($row = $result -> fetch_assoc()) $rows[] = $row;
Down in your Javascript code, add this at the top:
const data = <?= json_encode($rows, JSON_NUMERIC_CHECK) ?>;
You should end up with this in your page source:
const data = [{ "checkPID": 6, "mod1": 0, "mod2": 6, "mod3": 0, "mod4": 3, "mod5": 2, "mod6": 1, "idUsers": 1 }];
Now you can do this in your Chart setup:
data: Object.keys(data[0]).filter(key => key.startsWith("mod")).map(key => data[0][key]),

Related

Integrate PHP variables in Javascript [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 2 years ago.
I have this Javascript which outputs a chart with some values:
<script type="text/javascript">
//pie
var ctxP = document.getElementById("pieChart").getContext('2d');
var myPieChart = new Chart(ctxP, {
type: 'pie',
data: {
labels: ["Red", "Blue"],
datasets: [{
data: [10, 90],
backgroundColor: ["#F7464A", "#46BFBD"],
hoverBackgroundColor: ["#FF5A5E", "#5AD3D1"]
}]
},
options: {
responsive: true
}
});
</script>
I need to customize some values, as the ones in labels or data, coming from some calculations previously made in PHP.
What I tried so far was unsuccessfull, probably because I am missing something.
To simplify what I did, here the code:
//PHP code where I define some variables as strings
<?php
$color1 = "Black";
$color2 = "White";
?>
//Then comes again the Javascript code:
<script type="text/javascript">
//pie
var ctxP = document.getElementById("pieChart").getContext('2d');
var myPieChart = new Chart(ctxP, {
type: 'pie',
data: {
labels: [<?php echo $color1, $color2; ?>], //////////Here my modification
datasets: [{
data: [10, 90],
backgroundColor: ["#F7464A", "#46BFBD"],
hoverBackgroundColor: ["#FF5A5E", "#5AD3D1"]
}]
},
options: {
responsive: true
}
});
</script>
This does not work, but I do not understand why.
I also tried with:
<?php
$colors = array("Black", "White");
?>
passing the $colors variable, but nothing changes.
What kind of mistake am I making?
How can I fix this?
In a php file it can be done with json_encode
<?php
// your php code
?>
<script>
var jsObject = <?php
echo json_encode([
'my_variable1' => 'value1',
'my_variable2' => 'value2'
]);
?>
console.log(jsObject);
</script>

Morris.js Not showing any chart

i'm trying to make a morris.js line chart which displays the total amount of registered users.
The thing is that it won't show on my index.php.
I have all the javascript and css files imported.
Is there anyone that could give me a hand?
I'm very new to the javascript scene.
So simple answers are welcome haha.
Here is my code:
<?php
$connection = $stmt -> prepare("SELECT * FROM `user`");
$connection -> execute();
$chart_data = '';
while($row = $connection -> fetch(PDO::FETCH_ASSOC)){
$chart_data .= "{ year:'".$row['ID']."'
}";
}
$chart_data = substr($chart_data, 0, -2);
?>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">
<script stc="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
<script>
Morris.Bar({
element : 'chart',
data:[<?php echo $chart_data; ?>],
xkeys:'year',
ykeys:['users'],
});
</script>
<div class="container" style="width:900px;">
<h2 allign="center">Data grafiek</h2>
<br><br>
<div id="chart"></div>
</div>
Your Data should be in this format:
data: [
{ year: '2008', value: 20 },
{ year: '2009', value: 10 },
{ year: '2010', value: 5 },
{ year: '2011', value: 5 },
{ year: '2012', value: 20 }
],
I have change the library of jQuery. Putting the JS at the end of HTML code
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
<script>
$(document).ready(function(){
Morris.Bar({
element : 'chart',
data:[<?php echo $chart_data; ?>],
xkeys:'value',
ykeys:['year'],
labels: ['year']
});
});
</script>
And PHP code Should be not -2 it will be -1
while($row = mysqli_fetch_assoc($result)){
$id=$row['id'];
$val=$row['fname'];
$chart_data .= "{ year:'$id',value:'$val'},";
}
$chart_data = substr($chart_data, 0, -1);
Try this and share your console if you can

Google Column chart mysql php is not display

As I have written some of Javascript and MySQL for populate dynamic data for google chart, I have got few chart working but one chart is baffled me, I knew it should be working but I feel that I'm missing something, as it doesn't show at all.
error code displayed
Uncaught (in promise) ReferenceError: Amazon is not defined
at columnCharttotal (Dashboard.php:144)
at
Here is Javascript code
<script type="text/javascript">
//begin columns chart
google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(columnCharttotal);
function columnCharttotal() {
var data = google.visualization.arrayToDataTable([
["marketplace_name", "total_amount", {role: "style"}],
<?php
while (($rowResult = mysqli_fetch_array($totalresultchart, MYSQLI_ASSOC)) != NULL) {
?>
[ <?php echo $rowResult["marketplace_name"]; ?>, <?php echo $rowResult["total_amount"]; ?>, "blue"]
<?php
}
mysqli_free_result($totalresultchart);
?>
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"},
2]);
var options = {
title: "Total of all Europe sold",
height: 400,
bar: {groupWidth: "95%"},
legend: {position: "none"},
};
var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values"));
chart.draw(view, options);
}
//end of column chart
</script>
here is an HTML code
<div class="col-sm-4">
<div id="columnchart_values" style="width:100%"></div>
<br>
</div>
As Chrome Developer tools displayed show data on console
Look at this line;
[ <?php echo $rowResult["marketplace_name"]; ?>, <?php echo $rowResult["total_amount"]; ?>, "blue"]
Its outputting
[ Amazon.co.uk , 1231231, "Blue" ]
When it should output:
[ "Amazon.co.uk" , 1231231, "Blue" ]
Therefore; change the line too:
[ "<?php echo $rowResult["marketplace_name"]; ?>", <?php echo $rowResult["total_amount"]; ?>, "blue"]

HighChart Line Graph value from database

I want to draw one page with HighChart. I took data from database. I wrote it with json_encode. I can see what my $xxx has value. Its json format. But my graph is not working. I think var data = <?php echo json_encode($xxx); ?> doesnt work and return valur. Where do I mistake?
Here is my php code for database value:
<?php
$var = "SELECT SUBSTRING(KayitTarihi,1,4) AS year,SUBSTRING(KayitTarihi,6,2) AS month,SUBSTRING(KayitTarihi,9,2) AS day,SUBSTRING(KayitTarihi,12,2) AS saat,SUBSTRING(KayitTarihi,15,2) AS dakika,Guc FROM Urun WHERE Date(KayitTarihi)=\"".$link_m."\"";
$result = $mysqli->query($var);
$data = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
$no = 1;
$total_deger=count($data);
foreach($data as $dat)
{
$xxx ="[Date.UTC(".$dat['year'].",".$dat['month'].",".$dat['day'].",".$dat['saat'].",".$dat['dakika'].",00),".$dat['Guc']."]";
if($no < $total_deger)
{
echo ",";
}
echo json_encode($xxx);
}
//free memory associated with result
$result->close();
//close connection
$mysqli->close();
?>
And here is my highchart script:
<script>
$(function () {
var data = <?php echo $xxx; ?>;
Highcharts.chart('container', {
chart: {
zoomType: 'x'
},
title: {
text: 'USD to EUR exchange rate over time'
},
subtitle: {
text: document.ontouchstart === undefined ?
'Click and drag in the plot area to zoom in' : 'Pinch the chart to zoom in'
},
xAxis: {
type: 'datetime'
},
yAxis: {
title: {
text: 'Exchange rate'
}
},
legend: {
enabled: false
},
plotOptions: {
area: {
fillColor: {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops: [
[0, Highcharts.getOptions().colors[0]],
[1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
]
},
marker: {
radius: 2
},
lineWidth: 1,
states: {
hover: {
lineWidth: 1
}
},
threshold: null
}
},
series: [{
type: 'area',
name: 'USD to EUR',
data: [data]
}]
});
});
</script>
Edit: I edited json format. When I write just echo. Its just see one value.
Edit2: I have 9 value. My output is:
,,,,,,,,[Date.UTC(2016,11,15,10,28,00),0]
[Date.UTC(2016,11,15,14,25,00),0]
[Date.UTC(2016,11,15,14,25,00),0]
[Date.UTC(2016,11,15,14,27,00),17]
[Date.UTC(2016,11,15,18,32,00),54]
[Date.UTC(2016,11,15,18,32,00),54]
[Date.UTC(2016,11,15,18,33,00),93]
[Date.UTC(2016,11,15,18,33,00),34]
[Date.UTC(2016,11,15,18,34,00),34]
But when ı read docs for highchart my value must be
([
[Date.UTC(2016,11,15,10,28,00),0],
[Date.UTC(2016,11,15,14,25,00),0],
[Date.UTC(2016,11,15,14,25,00),0],
[Date.UTC(2016,11,15,14,27,00),17],
[Date.UTC(2016,11,15,18,32,00),54],
[Date.UTC(2016,11,15,18,32,00),54],
[Date.UTC(2016,11,15,18,33,00),93],
[Date.UTC(2016,11,15,18,33,00),34],
[Date.UTC(2016,11,15,18,34,00),34]
]);
Try wrapping it in quotes
var data = "<?php echo json_encode($xxx); ?>"
You should see this as an error in the console
Also you arent concatenating correctly. This means every time the loop runs you are overwriting the last entry stored in $xxx
$xxx = "[Date.UTC(".$dat['year'].",".$dat['month'].",".$dat['day'].",".$dat['saat'].",".$dat['dakika'].",00),".$dat['Guc']."]";
should be
$xxx .= "[Date.UTC(".$dat['year'].",".$dat['month'].",".$dat['day'].",".$dat['saat'].",".$dat['dakika'].",00),".$dat['Guc']."]";
Finally, change your loop to work like this
$xxx = '';
foreach($data as $dat){
// if not a blank string i.e. something added, add a comma to the end read for the next concatenation
if($xxx != '') $xxx .= ",";
// concatenate
$xxx .= "[Date.UTC(".$dat['year'].",".$dat['month'].",".$dat['day'].",".$dat['saat'].",".$dat['dakika'].",00),".$dat['Guc']."]";
}
// if not blank string, echo
if($xxx != ''){
echo json_encode($xxx);
}

Connecting Chart.js to MySQL database

I have this script in my html document which creates a chart using Chart.js. The data in it are manualy inserted ( The labels and the data in datasets). The data in datasets are now randomly generated numbers. But I need to somehow connect it with my MySQL database.
<script>
var randomScalingFactor = function(){ return Math.round(Math.random()*100)};
var barChartData = {
labels : ["January","February","March","April","May","June","July","January","February","March","April","May","June","July"],
datasets : [
{
fillColor : "rgba(23, 158, 3, 0.8)",
strokeColor : "rgba(24, 107, 2, 0.8)",
highlightFill: "rgba(24, 107, 2, 0.9)",
highlightStroke: "rgba(24, 107, 2, 1)",
data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
}
]
}
window.onload = function(){
var ctx2 = document.getElementById("canvas2").getContext("2d");
ctx2.canvas.width = 1000;
ctx2.canvas.height = 800;
window.myBar = new Chart(ctx2).Bar(barChartData, {
responsive : true
});
}
I call select query in Model and then send the result to my View.
And then in my View I can get to my data like this.
I used a table as an example.
<?php foreach ($this->list_excercise as $value) : ?>
<td><?= $value['data'] ?></td>
<td><?= $value['label'] ?></td>
<?php endforeach; ?>
So the data can be inserted into html like this, but how can I insert it into chart.js javascript? So instead of
labels: ["January", "February"]
I would have something like
labels: $array
I cannot figure out a simple way of getting the data to the script. Can anyone help me out with this? Thank you in advance.
If you have your data in a php array and your labels in another php array then you can just use the json_encode function to pass your data to chartjs.
With your $this->list_excercise you could do this :
<?php
$data = array();
$label = array();
foreach ($this->list_excercise as $value) :
$data[] = $value['data'];
$label[] = $value['label'];
endforeach;
?>
and then in your view/template :
var barChartData = {
labels : <?php echo json_encode($label) ?>,
datasets : [
{
fillColor : "rgba(23, 158, 3, 0.8)",
strokeColor : "rgba(24, 107, 2, 0.8)",
highlightFill: "rgba(24, 107, 2, 0.9)",
highlightStroke: "rgba(24, 107, 2, 1)",
data : <?php echo json_encode($data) ?>
}
]
}
I haven't run the code, but the idea is there as a snippet.
See if that helps.

Categories

Resources