使用 SQL 自动更新 ChartJs
Automatic update a ChartJs with SQL
所以我正在尝试对我的 Chart.Js 饼图进行自动更新,但我对如何进行有点困惑。
我的 .php 文件中有一个 MySQL
数据库,这是我从中获取 JS 变量的地方(它们在示例中只是硬编码)。在我加载页面的那一刻,我执行了一个 SQL 调用,然后 运行 PieChart(...)
函数与检索到的 SQL 数据。
但是我怎样才能有一个自动更新饼图的按钮,onclick?
我听说 ChartJS 有这个更新程序
myLineChart.data.datasets[0].data[2] = 50; // Would update the first dataset's value of 'March' to be 50
myLineChart.update(); // Calling update now animates the position of March from 90 to 50.
但是我该如何使用它呢?
我现在有一个 php 函数,它执行 SQL 调用和 returns 更新饼图所需的所有信息:
$OverviewResult = pieChartUpdater($FirstItemDD[0]);
这只需要在这些变量中实现
var Passed = "<?php echo $OverviewResult[0]; ?>";
var Failed = "<?php echo $OverviewResult[1]; ?>";
var Notrun = "<?php echo $OverviewResult[2]; ?>";
var Err = "<?php echo $OverviewResult[3]; ?>";
var Na = "<?php echo $OverviewResult[4]; ?>";
var PercentagePassed = "<?php echo $OverviewResult[5]; ?>";
var PercentageFailed = "<?php echo $OverviewResult[6]; ?>";
var PercentageNotrun = "<?php echo $OverviewResult[7]; ?>";
var PercentageError = "<?php echo $OverviewResult[8]; ?>";
var PercentageNa = "<?php echo $OverviewResult[9]; ?>";
然后js函数PieChart(...)
被执行
我是否应该在单击按钮时创建一个 PieChartUpdater()
函数,调用 SQL 函数然后更新 ChartJS 部分?或者它是如何工作的?
var Passed = "198";
var Failed = "37";
var Notrun = "0";
var Err = "0";
var Na = "0";
var PercentagePassed = "84.26";
var PercentageFailed = "15.74";
var PercentageNotrun = "0";
var PercentageError = "0";
var PercentageNa = "0";
/**
* Creates a PieChart overview of results
*
* @param {number} pass Amount of passed results
* @param {number} fail Amount of failed results
* @param {number} notRun Amount of not run results
* @param {number} err Amount of error results
* @param {number} nA Amount of not applicable results
* @param {number} percentagePassed Percentage of passed amount
* @param {number} percentageFailed Percentage of failed amount
* @param {number} percentageNotRun Percentage of not run amount
* @param {number} percentageError Percentage of error amount
* @param {number} percentageNA Percentage of not applicable amount
*/
function PieChart(pass, fail, notRun, err, nA, percentagePassed, percentageFailed, percentageNotRun, percentageError, percentageNA) {
window.chartColors = {
red: '#dc3545',
green: '#1cc88a',
blue: '#4e73df',
yellow: '#f6c23e',
black: '#5a5c69'
};
var config = {
type: 'pie',
data: {
datasets: [{
data: [
nA,
err,
notRun,
fail,
pass
],
backgroundColor: [
window.chartColors.black,
window.chartColors.yellow,
window.chartColors.blue,
window.chartColors.red,
window.chartColors.green,
],
label: 'Dataset 1'
}],
labels: [
percentageNA + "% NA",
percentageError + "% Error",
percentageNotRun + "% Not Run",
percentageFailed + "% Failed",
percentagePassed + "% Passed"
]
},
options: {
responsive: true
}
};
window.onload = function() {
var ctx = document.getElementById('chart-area').getContext('2d');
window.myPie = new Chart(ctx, config);
};
}
PieChart(Passed, Failed, Notrun, Err, Na, PercentagePassed, PercentageFailed, PercentageNotrun, PercentageError, PercentageNa);
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div id="canvas-holder" style="width:50%">
<div class="chartjs-size-monitor">
<div class="chartjs-size-monitor-expand">
<div class=""></div>
</div>
<div class="chartjs-size-monitor-shrink">
<div class=""></div>
</div>
</div>
<canvas id="chart-area" style="display: block; width: 762px; height: 381px;" width="762" height="381" class="chartjs-render-monitor"></canvas>
</div>
我正在尝试创建什么
嗯,您需要做一些清理和新步骤:
1。将您的代码分成几个文件:
src/config.php
: 你把你的数据库设置放在哪里
src/data-functions.php
: 存储一些DB查询函数。
index.php
:您的 HTML 页面。
chart-data.php
:仅检索 JSON. 中的新数据的服务
2。在 src/data-functions.php
中放入您的逻辑以检索 PHP 数组中的数据:
<?php
/**
* Get the pie chart data from the DB.
*
* @return array
*/
function getPieChartData()
{
// Do the SQL queries and return an array with the labels,
// values and colors. We'll be able to convert it to JS later.
$data = [
[
'value' => rand(50, 200),
'label' => '%.2f%% passed', // sprintf() format to inject pourcentage after.
'color' => '#1cc88a', // green
],
[
'value' => rand(0, 30),
'label' => '%.2f%% failed', // sprintf() format to inject pourcentage after.
'color' => '#dc3545', // red
],
[
'value' => rand(0, 3),
'label' => '%.2f%% not run', // sprintf() format to inject pourcentage after.
'color' => '#4e73df', // blue
],
[
'value' => rand(0, 10),
'label' => '%.2f%% NA', // sprintf() format to inject pourcentage after.
'color' => '#5a5c69', // gray
],
[
'value' => rand(0, 2),
'label' => '%.2f%% Error', // sprintf() format to inject pourcentage after.
'color' => '#f59f00', // orange
],
];
// Calculate the sum of the values so that we can calculate the % to put in the labels.
$sum = 0;
foreach ($data as $item) {
$sum += $item['value'];
}
// Walk accross the array to replace the labels by the calculated % in the label.
foreach ($data as $i => $item) {
$data[$i]['label'] = sprintf($item['label'], $item['value'] * 100 / $sum);
}
return $data;
}
3。在 index.php
中生成 HTML 和 JavaScript 代码
<?php
require 'src/config.php';
require 'src/data-functions.php';
// Get the data from the DB.
$data = getPieChartData();
// Convert the PHP array to a JS array.
$data_json = json_encode($data);
// The URL to get the data in JSON format.
$data_json_url = '/chart-data.php';
// Print your HTML and JavaScript which will be done once
// at the first page load.
?>
<div id="canvas-holder" style="width:50%">
<div class="chartjs-size-monitor">
<div class="chartjs-size-monitor-expand">
<div class=""></div>
</div>
<div class="chartjs-size-monitor-shrink">
<div class=""></div>
</div>
</div>
<canvas id="chart-area" style="display: block; width: 762px; height: 381px;" width="762" height="381" class="chartjs-render-monitor"></canvas>
<button id="chart-refresh-button">Refresh data</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script type="text/javascript">
/**
* @param array data The data for the pie chart.
* @param string jsonDataUrl The URL of the pie chart JSON data.
*/
function initPieChart(data, jsonDataUrl) {
var config = {
type: 'pie',
data: {
datasets: [{
label: 'Dataset 1',
data: [], // filled later
backgroundColor: [] // filled later
}],
labels: [] // filled later
},
options: {
responsive: true
}
};
/**
* Helper function to set the data values, labels and colors.
*
* @param array data The new data to use.
* @param object chart_data_to_set The chart.js data object to set.
*/
function setData(data, chart_data_to_set) {
// Loop over the data to fill the data object for chart.js.
data.forEach((item, i) => {
chart_data_to_set.datasets[0].data[i] = item.value;
chart_data_to_set.datasets[0].backgroundColor[i] = item.color;
chart_data_to_set.labels[i] = item.label;
});
}
// Fill the config with all our data, labels and colors.
setData(data, config.data);
// Once JS is loaded and DOM ready (images & CSS later).
document.addEventListener("DOMContentLoaded", () => {
var ctx = document.getElementById('chart-area').getContext('2d');
var myPie = new Chart(ctx, config);
var updateButton = document.getElementById('chart-refresh-button');
// Add a click handler on the refresh button.
updateButton.addEventListener('click', function(event) {
// Do an Ajax call to the server to just get the fresh data.
fetch(jsonDataUrl).then(response => {
return response.json();
})
.then(freshData => {
// Update the chart data with the fresh data.
setData(freshData, myPie.data);
myPie.update();
})
.catch(error => {
console.log('An error occured while fetching data from the server', error);
});
});
});
}
initPieChart(<?php echo $data_json; ?>, '<?php echo $data_json_url; ?>');
</script>
如您所见,PHP 数组在 json_encode()
的帮助下转换为 JavaScript 数组,并打印在 $data_json
的位置 HTML/JS输出。这样你就不需要所有的 JS 变量,这些变量会混淆和弄乱代码。此解决方案更通用,因为您可以在 PHP 中更改数据,而无需更改 JS 代码即可更新所有其他内容。
4。在 JSON
中创建 chart-data.php
到 return 的新数据
<?php
require 'src/config.php';
require 'src/data-functions.php';
// We won't print any HTML but just return the data in JSON.
$data = getPieChartData();
// Sent the correct MIME type for JSON and return the fresh data.
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data);
所以我正在尝试对我的 Chart.Js 饼图进行自动更新,但我对如何进行有点困惑。
我的 .php 文件中有一个 MySQL
数据库,这是我从中获取 JS 变量的地方(它们在示例中只是硬编码)。在我加载页面的那一刻,我执行了一个 SQL 调用,然后 运行 PieChart(...)
函数与检索到的 SQL 数据。
但是我怎样才能有一个自动更新饼图的按钮,onclick?
我听说 ChartJS 有这个更新程序
myLineChart.data.datasets[0].data[2] = 50; // Would update the first dataset's value of 'March' to be 50
myLineChart.update(); // Calling update now animates the position of March from 90 to 50.
但是我该如何使用它呢?
我现在有一个 php 函数,它执行 SQL 调用和 returns 更新饼图所需的所有信息:
$OverviewResult = pieChartUpdater($FirstItemDD[0]);
这只需要在这些变量中实现
var Passed = "<?php echo $OverviewResult[0]; ?>";
var Failed = "<?php echo $OverviewResult[1]; ?>";
var Notrun = "<?php echo $OverviewResult[2]; ?>";
var Err = "<?php echo $OverviewResult[3]; ?>";
var Na = "<?php echo $OverviewResult[4]; ?>";
var PercentagePassed = "<?php echo $OverviewResult[5]; ?>";
var PercentageFailed = "<?php echo $OverviewResult[6]; ?>";
var PercentageNotrun = "<?php echo $OverviewResult[7]; ?>";
var PercentageError = "<?php echo $OverviewResult[8]; ?>";
var PercentageNa = "<?php echo $OverviewResult[9]; ?>";
然后js函数PieChart(...)
被执行
我是否应该在单击按钮时创建一个 PieChartUpdater()
函数,调用 SQL 函数然后更新 ChartJS 部分?或者它是如何工作的?
var Passed = "198";
var Failed = "37";
var Notrun = "0";
var Err = "0";
var Na = "0";
var PercentagePassed = "84.26";
var PercentageFailed = "15.74";
var PercentageNotrun = "0";
var PercentageError = "0";
var PercentageNa = "0";
/**
* Creates a PieChart overview of results
*
* @param {number} pass Amount of passed results
* @param {number} fail Amount of failed results
* @param {number} notRun Amount of not run results
* @param {number} err Amount of error results
* @param {number} nA Amount of not applicable results
* @param {number} percentagePassed Percentage of passed amount
* @param {number} percentageFailed Percentage of failed amount
* @param {number} percentageNotRun Percentage of not run amount
* @param {number} percentageError Percentage of error amount
* @param {number} percentageNA Percentage of not applicable amount
*/
function PieChart(pass, fail, notRun, err, nA, percentagePassed, percentageFailed, percentageNotRun, percentageError, percentageNA) {
window.chartColors = {
red: '#dc3545',
green: '#1cc88a',
blue: '#4e73df',
yellow: '#f6c23e',
black: '#5a5c69'
};
var config = {
type: 'pie',
data: {
datasets: [{
data: [
nA,
err,
notRun,
fail,
pass
],
backgroundColor: [
window.chartColors.black,
window.chartColors.yellow,
window.chartColors.blue,
window.chartColors.red,
window.chartColors.green,
],
label: 'Dataset 1'
}],
labels: [
percentageNA + "% NA",
percentageError + "% Error",
percentageNotRun + "% Not Run",
percentageFailed + "% Failed",
percentagePassed + "% Passed"
]
},
options: {
responsive: true
}
};
window.onload = function() {
var ctx = document.getElementById('chart-area').getContext('2d');
window.myPie = new Chart(ctx, config);
};
}
PieChart(Passed, Failed, Notrun, Err, Na, PercentagePassed, PercentageFailed, PercentageNotrun, PercentageError, PercentageNa);
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div id="canvas-holder" style="width:50%">
<div class="chartjs-size-monitor">
<div class="chartjs-size-monitor-expand">
<div class=""></div>
</div>
<div class="chartjs-size-monitor-shrink">
<div class=""></div>
</div>
</div>
<canvas id="chart-area" style="display: block; width: 762px; height: 381px;" width="762" height="381" class="chartjs-render-monitor"></canvas>
</div>
我正在尝试创建什么
嗯,您需要做一些清理和新步骤:
1。将您的代码分成几个文件:
src/config.php
: 你把你的数据库设置放在哪里src/data-functions.php
: 存储一些DB查询函数。index.php
:您的 HTML 页面。chart-data.php
:仅检索 JSON. 中的新数据的服务
2。在 src/data-functions.php
中放入您的逻辑以检索 PHP 数组中的数据:
<?php
/**
* Get the pie chart data from the DB.
*
* @return array
*/
function getPieChartData()
{
// Do the SQL queries and return an array with the labels,
// values and colors. We'll be able to convert it to JS later.
$data = [
[
'value' => rand(50, 200),
'label' => '%.2f%% passed', // sprintf() format to inject pourcentage after.
'color' => '#1cc88a', // green
],
[
'value' => rand(0, 30),
'label' => '%.2f%% failed', // sprintf() format to inject pourcentage after.
'color' => '#dc3545', // red
],
[
'value' => rand(0, 3),
'label' => '%.2f%% not run', // sprintf() format to inject pourcentage after.
'color' => '#4e73df', // blue
],
[
'value' => rand(0, 10),
'label' => '%.2f%% NA', // sprintf() format to inject pourcentage after.
'color' => '#5a5c69', // gray
],
[
'value' => rand(0, 2),
'label' => '%.2f%% Error', // sprintf() format to inject pourcentage after.
'color' => '#f59f00', // orange
],
];
// Calculate the sum of the values so that we can calculate the % to put in the labels.
$sum = 0;
foreach ($data as $item) {
$sum += $item['value'];
}
// Walk accross the array to replace the labels by the calculated % in the label.
foreach ($data as $i => $item) {
$data[$i]['label'] = sprintf($item['label'], $item['value'] * 100 / $sum);
}
return $data;
}
3。在 index.php
中生成 HTML 和 JavaScript 代码
<?php
require 'src/config.php';
require 'src/data-functions.php';
// Get the data from the DB.
$data = getPieChartData();
// Convert the PHP array to a JS array.
$data_json = json_encode($data);
// The URL to get the data in JSON format.
$data_json_url = '/chart-data.php';
// Print your HTML and JavaScript which will be done once
// at the first page load.
?>
<div id="canvas-holder" style="width:50%">
<div class="chartjs-size-monitor">
<div class="chartjs-size-monitor-expand">
<div class=""></div>
</div>
<div class="chartjs-size-monitor-shrink">
<div class=""></div>
</div>
</div>
<canvas id="chart-area" style="display: block; width: 762px; height: 381px;" width="762" height="381" class="chartjs-render-monitor"></canvas>
<button id="chart-refresh-button">Refresh data</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script type="text/javascript">
/**
* @param array data The data for the pie chart.
* @param string jsonDataUrl The URL of the pie chart JSON data.
*/
function initPieChart(data, jsonDataUrl) {
var config = {
type: 'pie',
data: {
datasets: [{
label: 'Dataset 1',
data: [], // filled later
backgroundColor: [] // filled later
}],
labels: [] // filled later
},
options: {
responsive: true
}
};
/**
* Helper function to set the data values, labels and colors.
*
* @param array data The new data to use.
* @param object chart_data_to_set The chart.js data object to set.
*/
function setData(data, chart_data_to_set) {
// Loop over the data to fill the data object for chart.js.
data.forEach((item, i) => {
chart_data_to_set.datasets[0].data[i] = item.value;
chart_data_to_set.datasets[0].backgroundColor[i] = item.color;
chart_data_to_set.labels[i] = item.label;
});
}
// Fill the config with all our data, labels and colors.
setData(data, config.data);
// Once JS is loaded and DOM ready (images & CSS later).
document.addEventListener("DOMContentLoaded", () => {
var ctx = document.getElementById('chart-area').getContext('2d');
var myPie = new Chart(ctx, config);
var updateButton = document.getElementById('chart-refresh-button');
// Add a click handler on the refresh button.
updateButton.addEventListener('click', function(event) {
// Do an Ajax call to the server to just get the fresh data.
fetch(jsonDataUrl).then(response => {
return response.json();
})
.then(freshData => {
// Update the chart data with the fresh data.
setData(freshData, myPie.data);
myPie.update();
})
.catch(error => {
console.log('An error occured while fetching data from the server', error);
});
});
});
}
initPieChart(<?php echo $data_json; ?>, '<?php echo $data_json_url; ?>');
</script>
如您所见,PHP 数组在 json_encode()
的帮助下转换为 JavaScript 数组,并打印在 $data_json
的位置 HTML/JS输出。这样你就不需要所有的 JS 变量,这些变量会混淆和弄乱代码。此解决方案更通用,因为您可以在 PHP 中更改数据,而无需更改 JS 代码即可更新所有其他内容。
4。在 JSON
中创建chart-data.php
到 return 的新数据
<?php
require 'src/config.php';
require 'src/data-functions.php';
// We won't print any HTML but just return the data in JSON.
$data = getPieChartData();
// Sent the correct MIME type for JSON and return the fresh data.
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data);