I’ve been debugging this some time now and probably 2 hours now. I want to display the line graph of chart.js the revenue for the past 15 days.
I have a function to get the ajax result for the previous days. This is the js script I made.
// Function to fetch revenue data from PHP script
function fetchRevenueData() {
$.ajax({
url: '../config/tables/semi_weekly_revenue.php',
dataType: 'json',
success: function(data) {
var revenueValues = labels.map(function(date) {
return data[date] || 0;
});
myLineChart.data.datasets[0].data = revenueValues;
myLineChart.update();
},
error: function(xhr, status, error) {
console.error('Error fetching revenue data:', error);
}
});
}
the line graph:
// Area Chart Example
var ctx = document.getElementById("myAreaChart");
var myLineChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: "Revenue",
lineTension: 0.3,
backgroundColor: "rgba(2,117,216,0.2)",
borderColor: "rgba(2,117,216,1)",
pointRadius: 5,
pointBackgroundColor: "rgba(2,117,216,1)",
pointBorderColor: "rgba(255,255,255,0.8)",
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(2,117,216,1)",
pointHitRadius: 50,
pointBorderWidth: 2,
data: [],
}],
},
options: {
scales: {
xAxes: [{
time: {
unit: 'date'
},
gridLines: {
display: false
},
ticks: {
maxTicksLimit: 7
}
}],
yAxes: [{
ticks: {
min: 0,
max: 40000,
maxTicksLimit: 5
},
gridLines: {
color: "rgba(0, 0, 0, .125)",
}
}],
},
legend: {
display: false
}
}
});
//The fetchRevenueData function will update the Linechart upon called.
fetchRevenueData();
my php query script looks like this:
// Query to fetch total revenue for each of the past 15 days
$query = "SELECT
DATE_FORMAT(sale_date, '%Y-%m-%d') AS date,
SUM(total_amount) AS total_revenue
FROM sales
WHERE sale_date >= DATE_SUB(CURRENT_DATE(), INTERVAL 15 DAY)
GROUP BY date
ORDER BY date";
$stmt = $pdo->query($query);
// Fetch revenue data and populate the revenueData array
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$revenueData[$row['date']] = $row['total_revenue'];
}
// Return revenue data as JSON
echo json_encode($revenueData);
Did I miss something? I’ve read the documentation about data passing and maybe I miss something. I’m still learning JavaScript now. Thanks!
I expect the result to show the Line Graph similar to the bar graph but it will on semi-weekly Forecast of revenue for the past 15 days.