javascript - Chartjs dynamic chart return both x & y axis undefined
I am new to chartjs. After spend some time checking tutorials I came up codes as following and it's giving meundefined
result bothx
andy
axis. I can manage to get static data working i.e. if put down month ony-axis
and charts display fine. Any help is greatly appreciated. By the way I am using chartjsversion 2.1.4.
data.php:
<?php
//setting header to json
header('Content-Type: application/json');
include_once 'includes/db_connect.php';
$query = sprintf("SELECT FiscalPeriod, SUM(DollarsSold) AS Sold
FROM ar_customersalespersonhistory
WHERE FiscalYear = '2017'
GROUP BY FiscalPeriod
ORDER BY FiscalPeriod
");
//execute query
$result = $connection->query($query);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//free memory associated with result
$result->close();
//close connection
$connection->close();
//now print the data
print json_encode($data);
?>
Output from data.php:
[{
"FiscalPeriod": "01",
"Sold": "357508.03"
}, {
"FiscalPeriod": "02",
"Sold": "393790.14"
}, {
"FiscalPeriod": "03",
"Sold": "407346.07"
}, {
"FiscalPeriod": "04",
"Sold": "557704.12"
}, {
"FiscalPeriod": "05",
"Sold": "555916.68"
}, {
"FiscalPeriod": "06",
"Sold": "422659.26"
}, {
"FiscalPeriod": "07",
"Sold": "297766.49"
}, {
"FiscalPeriod": "08",
"Sold": "448256.07"
}, {
"FiscalPeriod": "09",
"Sold": "510020.86"
}, {
"FiscalPeriod": "10",
"Sold": "325525.30"
}, {
"FiscalPeriod": "11",
"Sold": "89214.27"
}]
And javascript:
$(document).ready(function() {
$.ajax({
url: '/registration/sales_general.php',
method: 'GET',
// dataType: 'json',
success: function(data) {
// console.log(data);
var month = [];
var sold = [];
for (var i in data) {
month.push(data[i].FiscalPeriod);
sold.push(data[i].Sold);
}
console.log(month);
console.log(sold);
var chartdata = {
// labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
labels: month,
datasets: [{
label: '2017',
backgroundColor: '#26B99A',
// data: [33,24,25,19,46,99,21]
data: sold
}]
};
var ctx = $('#mybarChart1');
ctx.height = 70;
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});
Answer
Solution:
Your
chartdata
object doesn't contain valid ChartJS optionsThis should work:
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: you must enable the openssl extension in your php.ini to load information from https://repo.packagist.org
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.