Connecting Chart.js to MySQL database - javascript

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.

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>

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

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]),

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

Import data from Database to JS file

I am new to .js files and their use, I am trying to update charts that uses JS. What I need or trying to do is import information from my database to use it in my JS file to populate the chart. Here is the chart code and file name.
File Name charjs_custom.js
/*Polar chart*/
var polarElem = document.getElementById("polarChart");
var data3 = {
datasets: [{
data: [
20,
16,
7,
3,
40
],
backgroundColor: [
"#7E81CB",
"#1ABC9C",
"#B8EDF0",
"#B4C1D7",
"#01C0C8"
],
hoverBackgroundColor: [
"#a1a4ec",
"#2adab7",
"#a7e7ea",
"#a5b0c3",
"#10e6ef"
],
label: 'My dataset' // for legend
}],
labels: [
"Blue",
"Green",
"Light Blue",
"grey",
"Sea Green"
]
};
new Chart(polarElem, {
data: data3,
type: 'polarArea',
options: {
elements: {
arc: {
borderColor: ""
}
}
}
});
I need to alter the "data" and "label" sections using information from my DB, from what I have read I need to create a php file to retrieve the informationbut how do i convert it to JS and how do I tell it what information to use in the JS file. Also linking the "data" and "label" sections so the information will correspond to my tables
Tables I want to use is: make: id~count
File Name chart_test.php
<?php
//database
$host="my_host"; // Host name
$username="my_username"; // Mysql username
$password="my_password"; // Mysql password
$db_name="my_database"; // Database name
//get connection
$mysqli = new mysqli($host, $username, $password, $db_name);
if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}
//query to get data from the table
$query = sprintf("SELECT * FROM bureau GROUP BY make ");
//execute query
$result = $mysqli->query($query);
//close connection
$mysqli->close();
//now print the data
print json_encode($data);
?>
you can interchange data between php backend and js frontend using JSON format. However i urge you to use nodejs as a backend service. it will integrate seamlessly with your js code.
Without really knowing anything about your data source, it would typically work like the following.
<?php
// Lets say your managed to convert your data from your database into something like.
$graph = [
'data' => [20, 16, 7, 3, 40],
'background' => ['#7E81CB', '#1ABC9C', '#B8EDF0', '#B4C1D7', '#01C0C8'],
'hover' => ['#a1a4ec', '#2adab7', '#a7e7ea', '#a5b0c3', '#10e6ef'],
'labels' => ['Blue', 'Green', 'Light Blue', 'Grey', 'Sea Green']
];
?>
var polarElem = document.getElementById("polarChart");
var data3 = {
datasets: [{
data: <?php echo json_encode($graph['data']); ?>,
backgroundColor: <?php echo json_encode($graph['background']); ?>,
hoverBackgroundColor: <?php echo json_encode($graph['hover']); ?>,
label: 'My dataset'
}],
labels: <?php echo json_encode($graph['labels']); ?>
};
So if I understand the mapping of the database, I would do:
<?php
//database
$host="my_host"; // Host name
$username="my_username"; // Mysql username
$password="my_password"; // Mysql password
$db_name="my_database"; // Database name
//get connection
$mysqli = new mysqli($host, $username, $password, $db_name);
if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}
//query to get data from the table
$query = sprintf("SELECT * FROM bureau GROUP BY make ");
//execute query
$result = $mysqli->query($query);
// Define configuration array
$config = array(
'datasets' => array(
array(
'data' => array(),
'backgroundColor' => array(), // This could be statically loaded, or dynamic if the DB has colors
'hoverBackgroundColor' => array(), // This could be statically loaded, or dynamic if the DB has colors
'label' => 'My Dataset'
)
),
'labels' => array()
);
// Loop through database result and add
while($row=mysqli_fetch_assoc($result)){
array_push($config['labels'], $row['make']); // Add label
array_push($config['datasets'][0]['data'], $row['totalValue']); // Add value
}
//close connection
$mysqli->close();
//now print the data
echo json_encode($config);
What you ultimately do with that config depends on how you're loading this chart. It could be an AJAX request that you would then use the result of in place of data3 such as:
$.get( "chart_test.php", function( data ) {
new Chart(polarElem, {
data: data,
type: 'polarArea',
options: {
elements: {
arc: {
borderColor: ""
}
}
}
});
}, "json" );
Or embedded into a php file so that instead of printing the json_encode($config); you would create the entire script:
new Chart(polarElem, {
data: <?= json_encode($config) ?>,
type: 'polarArea',
options: {
elements: {
arc: {
borderColor: ""
}
}
}
});
It all depends on the setup you have thus far.

Converting PHP array into JQuery data

I have encountered a little of a problem while trying to convert PHP array into jQuery. I have read a lot of threads on forum and I still cannot figure out what's wrong.
My PHP code that's basically for adding last 7 dates into array and assigning "a" and "b" to same value just for tests
$dni = array();
for($i =7; $i>0; $i--){
$dzien = date("Y-m-d", strtotime($i." day"));
$d->y = $dzien;
$chart = mysql_query("SELECT COUNT(*) FROM kolejka WHERE data LIKE '$dzien' AND odbyta = '0'", $link);
while($c = mysql_fetch_array($chart, MYSQL_ASSOC))
{
$xdi = $c['COUNT(*)'];
}
$d->a = $xdi;
$d->b = $xdi;
$dni[] = $d;
}
$data = json_encode($dni);
My jQuery code that's supposed to generate a chart:
var ar = <?php echo json_encode($data); ?>;
alert(ar);
Morris.Bar({
element: 'pacjenci-chart',
data: ar,
xkey: 'y',
ykeys: ['a', 'b'],
labels: ['New', 'Old'],
barColors: ['#33414E', '#1caf9a'],
gridTextSize: '10px',
hideHover: true,
resize: true,
gridLineColor: '#E5E5E5'
});
If I put into "data" a non-dynamic content like:
data: [
{ y: 'Oct 10', a: 75, b: 35 },
{ y: 'Oct 11', a: 64, b: 26 },
{ y: 'Oct 12', a: 78, b: 39 },
{ y: 'Oct 13', a: 82, b: 34 },
{ y: 'Oct 14', a: 86, b: 39 },
{ y: 'Oct 15', a: 94, b: 40 },
{ y: 'Oct 16', a: 96, b: 41 }
],
It works just fine.
An output of
var ar = <?php echo json_encode($data) ?>;
is
var ar = "[{\"y\":\"2017-03-19\",\"a\":\"0\",\"b\":\"0\"},{\"y\":\"2017-03-19\",\"a\":\"0\",\"b\":\"0\"},{\"y\":\"2017-03-19\",\"a\":\"0\",\"b\":\"0\"},{\"y\":\"2017-03-19\",\"a\":\"0\",\"b\":\"0\"},{\"y\":\"2017-03-19\",\"a\":\"0\",\"b\":\"0\"},{\"y\":\"2017-03-19\",\"a\":\"0\",\"b\":\"0\"},{\"y\":\"2017-03-19\",\"a\":\"0\",\"b\":\"0\"}]";
arent you doing json-encode twice here?
$data = json_encode($dni);
var ar = <?php echo json_encode($data); ?>;
Get rid of one of these and it should just work like this.
It is slightly obvious because of all the extra escape's to encode a json string again it will be converted to a string :-). Just echo the $data variable.
You encoded the array twice - first in PHP then in jQuery.
var ar = <?php echo json_encode($data); ?>;
remove json_encode()
var ar = <?php echo $data; ?>;

Categories

Resources