In my controller I create the array to be charted
function chart() {
$results = $this->Visit->query(
"SELECT date(visits.created) as visit_date,
Count(visits.id) AS count_visits
FROM visits
GROUP BY date(visits.created)"
);
foreach($results AS $result) {
$row = array(
$result[0]['visit_date'],
$result[0]['count_visits']
);
$chartData[] = json_encode($row);
}
pr($chartData);
}
pr($chartData) gives following array
Array
(
[0] => ["2012-07-11","5"]
[1] => ["2012-07-13","1"]
[2] => ["2012-07-14","1"]
)
in chart view i have
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create the data table.
var data = google.visualization.arrayToDataTable($chartData);
var options = {
title: 'Visits by Date',
hAxis: {title: 'Date', titleTextStyle: {color: 'black'}}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
but this doesn’t get me a chart .. no errors … just no chart ..
if I manually type in an array to test my view, it works fine … eg if i replace ..
var data = google.visualization.arrayToDataTable($chartData);
with the following format from Google Chart example it generates a nice column chart
var data = google.visualization.arrayToDataTable([
['Date', 'Count'],
['2012-07-11', 5],
['2012-07-13', 1],
['2012-07-14', 1]
]);
couple of questions:
– how do i get the header titles in the var data array?
– do double quotes or single quotes in array make a difference?
– am i passing the array $chartData from php to Google chart javascript correctly?
– the Google example has ‘[]’ around the array, how do i get those around my array too?
(bwt, i know all about cakephp’s Find(all) but I just got lost in documentation about how to get what i wanted and sql was much easier )
you are using json_encode in your controller, but in your view you are using –
json_encode creates json object, not and javascript array.
using json_encode in your controller function chart() try:
in your view use :