I wanted to make my chart script an external file but I never used ajax before and would like some help on how it works, my chart and everything works fine linked to a database, I just wanted to make the js file external.
Here is the php code:
<?php
//delcare and run sql
$sql = "SELECT prices, generations from products";
$result = mysqli_query($con, $sql);
//variables
$dataX = "";
$dataY = "";
//Loop to get the data
While($row=mysqli_fetch_assoc($result)){
$dataX = $dataX."'".$row['generations']."',";
$dataY = $dataY."'".$row['prices']."',";
}
//Trim your string for white spaces and for comma at the end
$dataX=trim($dataX,",");
$dataY=trim($dataY,",");
?>
And here is the javascript code:
<script type="text/javascript">
var myChart = document.getElementById('myChart').getContext('2d');
var data = {
type: 'bar', //bar, horizontablbar, pie, doughnut, radar, polararea
data: {
labels: [ <?php echo $dataX?> ],
datasets: [{
label: 'product sales',
data: [ <?php echo $dataY ?> ],
backgroundColor: [,'tomato', 'green','blue','cyan'],borderWidth: 1,
borderColour: 'grey', hoverBorderColor: 'black'
}],
},
options: {
title: {
display: true,
text: 'Product Sales Report'
},
legend: {
display: false,
},
scales: {
yAxes: [{
display: true,
ticks: {
beginAtZero: true,
steps: 10,
stepValue: 5,
}
}]
}
}
}
var Chart = new Chart(myChart, data);
</script>
2 Answers 2
You need to create a file that serves a JSON response (for example) of your data, then access it using XHR request (or easily, use jQuery's AJAX) to render the data on your chart.
Using the code you provided, you should create another PHP file that prints the a JSON response:
<?php
$sql = "SELECT prices, generations from products";
$result = mysqli_query($con, $sql);
//variables
$dataX = array();
$dataY = array();
//Loop to get the data
while($row = mysqli_fetch_assoc($result)){
array_push($dataX, $row['generations'];
array_push($dataY, $row['prices'];
}
header('Content-Type: application/json');
echo json_encode(array(
"dataX" => $dataX,
"dataY" => $dataY
));
Let's assume you called this file data.php and placed it on the root directory.
You now need to access the file using a jQuery AJAX request and render your chart using this data:
$.ajax({
url: '/data.php',
method: 'GET',
success: function(response) {
var dataX = response.dataX;
var dataY = response.dataY;
renderHtmlChart(dataX, dataY);
}
});
Hope you can find the right way to create the renderHtmlChart function :)
9 Comments
head tag: <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>Managed to fix the issues was a simple variable name that wasn't correct to display the chart.
Index.php file
<html>
<?php
include "connection.php";
?>
<head>
</head>
<body>
<div id="navigation">
<div id="nava">
<a href="">Home</a></li>
<a href="">News</a></li>
<a href="">Contact</a></li>
<a href="">About</a></li>
</div>
</div>
<form method="get">
<select name="year" size="1" >
<option value="2014">2014</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
</select>
<input type="submit"></input>
</form>
<canvas id="myChart"></canvas>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script type="text/javascript" src="chart.js"></script>
<script type="text/javascript" src="styles.js"></script>
</body>
</html>
data.php file
<?php
include "connection.php";
$sql = "SELECT Bookings, Destination from topflights";
$result = mysqli_query($con, $sql);
//variables
$dataX = array();
$dataY = array();
//Loop to get the data
while($row = mysqli_fetch_assoc($result)){
array_push($dataX, $row['Destination']);
array_push($dataY, $row['Bookings']);
}
header('Content-Type: application/json');
echo json_encode(array(
"dataX" => $dataX,
"dataY" => $dataY));
?>
chart.js file
function renderHtmlChart() {
var universalOptions = {
responsive: true,
title: {
display: true,
text: "Top 5 Flights Booked in the Year"
},
legend: {
display: false,
},
scales: {
xAxes: [{
display: true,
}],
yAxes: [{
display: true,
ticks: {
beginAtZero: true,
}
}],
}
}
$.ajax({
url: 'data.php',
method: 'GET',
success: function(response) {
var dataX = response.dataX;
var dataY = response.dataY;
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: dataX,
datasets: [{
label: 'top flights',
data: dataY,
backgroundColor: ['tomato', 'green', 'blue', 'cyan', 'orange'],
borderWidth: 1,
borderColour: 'grey',
hoverBorderColor: 'black'
}],
},
options: universalOptions
}
)
},
error: function(response) {
alert('ajax failed');
console.log(response);
}
});
}
$(document).ready(function() {
renderHtmlChart();
});