I finally made it working with AJAX but the problem is, it's not real-time whenever I change some data in phpMyAdmin, I need to refresh it on the website.
Here's my code: ajax.js
$(document).ready(function() {
$.ajax({
url: "http://localhost/projectZeus/private/data.php",
method: "GET",
async: true,
success: function(data) {
var energy = [];
for(var i in data) {
energy.push(data[i].energyPercent);
}
var chartdata = {
labels: ["Jan", "Feb", "Mar", "Apr", "May"],
datasets: [{
label: "Harvested",
lineTension: 0.3,
backgroundColor: "rgba(2,117,216,0.2)",
borderColor: "rgba(2,117,216,1)",
pointRadius: 6,
pointBackgroundColor: "rgba(2,117,216,1)",
pointBorderColor: "rgba(255,255,255,0.8)",
pointHoverRadius: 8,
pointHoverBackgroundColor: "rgba(2,117,216,1)",
pointHitRadius: 20,
pointBorderWidth: 2,
data: energy
}]
};
var ctx = $("#AreaChart");
var lineChart = new Chart(ctx, {
type: 'line',
data: chartdata
});
},
error: function(data) {
}
});
});
Here's my code in data.php
<?php
require_once('initialize.php');
header('Content-Type: application/json');
global $db;
$sql = "SELECT energyPercent FROM energy";
$result = mysqli_query($db, $sql);
$data = array();
foreach($result as $row) {
$data[] = $row;
}
mysqli_free_result($result);
echo json_encode($data);
?>
How can I get it to real-time without refreshing the page? Please help, thanks!