Reputation:
I have .php file and I have js file. I am trying to make bar chart. Now I have selected some data to my database. and now I don't know how can I get data from .php file to .js file.
I have this code:
//.js file
var data, options;
// replace this data with my selected data
data = {
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
series: [
[19, 29, 28, 44, 39, 48, 54],
]
};
options = {
height: 300,
showArea: true,
showLine: true,
showPoint: true,
fullWidth: true,
axisX: {
showGrid: false
},
lineSmooth: false,
};
new Chartist.Line('#headline-chart', data, options);
/PHP FILE/
$chart6 = $controller->runQuery("SELECT DATE(pay_date) `DATE`, SUM(amount) daily_amount, DATE_FORMAT(pay_date,'%a') DAYNAME FROM tbl_paid WHERE DATE(pay_date) BETWEEN DATE(:today) - INTERVAL 1 WEEK AND DATE(:today) GROUP BY DATE(pay_date);");
$chart6->execute(array(":today"=>$today));
while($fetch = $chart6->fetch(PDO::FETCH_ASSOC))
{
$data ="{labels:".$fetch['DATE']."-".$fetch['DAYNAME']." series:".$fetch['daily_amount']."}";
}
Upvotes: 1
Views: 5583
Reputation: 5745
You can read about ajax in javascript and make an ajax request that gets the json object from PHP then process that in your javascript:
Example (with some improvement to your PHP code)
PHP
$chart6 = $controller->runQuery("SELECT DATE(pay_date) `DATE`, SUM(amount) daily_amount, DATE_FORMAT(pay_date,'%a') DAYNAME FROM tbl_paid WHERE DATE(pay_date) BETWEEN DATE(:today) - INTERVAL 1 WEEK AND DATE(:today) GROUP BY DATE(pay_date);");
$chart6->execute(array(":today"=>$today));
$labels = array();
$series = array()
while($fetch = $stmt->fetch(PDO::FETCH_ASSOC)) {
$labels[] = $fetch['DAYNAME'];
$series0[] = $fetch['daily_amount'];
}
$series[] = $series0;
// add the labels and series to an array, then convert that to json
$data = array('labels' => $labels, 'series' => $series);
echo json_encode($data);
JS:
// Make an Ajax request, here I am using jQuery $.getJSON but you can use $.get or $.post if you need to have it as a post request, or even $.ajax
$.getJSON('https://example.com/database_fetch_page.php', function(data) {
new Chartist.Line('#headline-chart', data, options);
});
Upvotes: 1