I'm trying to work with Chart.js for the first time. I already understand how it works, but I now want to pass my data from php to javascript.
This is what I have:
PHP
//send the string values to javascript
$grade_range_string = mb_substr($grade_range_string, 0, -2);
$percentage_count_string = implode(", ", $percentage_count_array);
//chart colors
$grade_chart_colors_string = "";
$grade_chart_colors_array = grade_chart_colors();
foreach ($grade_chart_colors_array as $color) {
$grade_chart_colors_string .= "'".$color."'" . ", ";
}
$grade_chart_colors_string = mb_substr($grade_chart_colors_string, 0, -2);
HTML
<span id="grade_range_string" data-value="<?php echo $grade_range_string; ?>"></span>
<span id="percentage_count_string" data-value="<?php echo $percentage_count_string; ?>"></span>
<span id="grade_chart_colors_string" data-value="<?php echo $grade_chart_colors_string; ?>"></span>
<canvas id="broadsheet_piechart"></canvas>
Javascript:
// Pie chart
if ( $('#broadsheet_piechart').length ) {
var grade_range_string = $('#grade_range_string').attr('data-value');
var percentage_count_string = $('#percentage_count_string').attr('data-value');
var grade_chart_colors_string = $('#grade_chart_colors_string').attr('data-value');
//debug
console.log(grade_range_string);
console.log(percentage_count_string);
console.log(grade_chart_colors_string);
var ctx = document.getElementById("broadsheet_piechart");
var data = {
datasets: [{
data: [percentage_count_string],
backgroundColor: [grade_chart_colors_string],
label: 'My dataset' // for legend
}],
labels: [grade_range_string]
};
var broadsheet_piechart = new Chart(ctx, {
data: data,
type: 'pie',
options: {
animation: {
duration: 0
}
}
});
}
//debug
console.log(data);
In the console window, the 3 variables grade_range_string, percentage_count_string, grade_chart_colors_string return the data as formatted, but the datasets data variable encloses the data in double quotes like this:
data: ["'Item 1', 'Item 2', 'Item 3', 'Item etc'"]
Same for backgroundColor and labels.
This ruins my pie...
Why is that happening, and how do I get rid of the quotes? Is there a better way of achieving this? Thanks.