Array To String Conversion While Using Canvas Js In Yii2
Solution 1:
You should encode the php array to json outside the heredoc and supply the output to the javascript part, and you dont use the php tags but use curly braces {}
to parse values from the variable inside the heredoc.
See below it should work correctly
<?PHP
$dataPoints1 = json_encode($dataPoints1, JSON_NUMERIC_CHECK);
$dataPoints2 = json_encode($dataPoints1, JSON_NUMERIC_CHECK);
$script = <<< JS
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer1", {
animationEnabled:true,
theme:"light2",
title:{
text:"Average Amount Spent on Real and Artificial X-Mas Trees in U.S."
},
legend:{
cursor:"pointer",
verticalAlign:"center",
horizontalAlign:"right",
itemclick: toggleDataSeries
},
data: [{
type:"column",
name:"Real Trees",
indexLabel:"{y}",
yValueFormatString:"$#0.##",
showInLegend:truedataPoints: {$dataPoints1}
},{
type:"column",
name:"Artificial Trees",
indexLabel:"{y}",
yValueFormatString:"$#0.##",
showInLegend:true,
dataPoints: {$dataPoints2}
}]
});
chart.render();
function toggleDataSeries(e){
if (typeof(e.dataSeries.visible) === "undefined"|| e.dataSeries.visible) {
e.dataSeries.visible = false;
}
else{
e.dataSeries.visible = true;
}
chart.render();
}
}
JS;
$this->registerJs($script);
?>
Solution 2:
@Faisal, You are passing a String(echo prints anything as strings) in "dataPoints" but its accepts JSON Array.
You need to parse the json string to convert it into a valid JSON. Use JSON.parse() function and modify your code in Javascript as below.
dataPoints: JSON.parse()
Updated:
First take the dataPoints from PHP in a variable before initialising the chart. Then pass this variable within chart configuration. Also try with JSON.parse().
If it still doesn't work, print this new variable in Console and check your output and post that here
Post a Comment for "Array To String Conversion While Using Canvas Js In Yii2"