Friday, March 1, 2019

javascript - Highcharts Pie chart data Format via php



Am using Highcharts for pie chart. Below is the JS code for it :




$(document).ready(function () {
var chart;

var graphData = $("#graphContentdata").val();
console.log(graphData);
var options = {
chart: {
renderTo: 'graphContainer',
plotBackgroundColor: null,
plotBorderWidth: null,

plotShadow: false
},
title: {
text: 'SOV'
},
tooltip: {
formatter: function() {
return ''+ this.point.name +': '+ this.percentage +' %';
}
},

plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
formatter: function() {
return ''+ this.point.name +': '+ this.percentage +' %';

}
}
}
},
series: [{
type: 'pie',
name: 'Browser share',
data: []
}]
}


chart = new Highcharts.Chart(options);
chart.series[0].setData("["+graphData+"]");

});


And PHP Code for generating the Data :



foreach ($sumArray as $key=>$value)

{
$sumArray[$key] = array_sum($value);
$percent = (number_format(($sumArray[$key]/$sovGrandTotal)*100,2));

$data[] = "['$key', $percent]";
}
$data = join(",", $data);

?>




The Data format Am getting is :



['www.quora.com', 0.23],['www.slideshare.net', 0.25],['me', 99.52]


Problem is :



chart.series[0].setData("["+graphData+"]");



not creating graph, but if i copy paste the value from console at palce of graphData variable, its working like:



chart.series[0].setData([['www.quora.com', 0.23],['www.slideshare.net', 0.25],['me', 99.52]]);


is working.



What's the mistake am doing here???



Answer



The problem is your are passing your data as a String when you are using



chart.series[0].setData("["+graphData+"]");


You need to set your data as an Array. You could do that by converting your String using eval:



chart.series[0].setData(eval("["+graphData+"]"));



You could also use jQuery to convert your String to JSON, but in that case you must use double quotes to open and close Strings:



$.parseJSON("[[\"www.quora.com\", 0.23],[\"www.slideshare.net\", 0.25],[\"me\", 99.52]]");

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...