Highcharts: Updating a Pie with ajax - javascript

I want to update the pie's data when the li is clicked. If data.php $cid get the value fixed value it works. Example : user_student.cid = 1 will work. If i use user_student.cid = $cid it doesn't work. Does anyone have any idea?
Thanks you,pquest.
But there have some problems.If I use fixed value 1 ,the alert value is: [["apple",1],["banana",2],["orange",3]] and the pie is working. If I use $cid value(if $cid value is 1) , the value alert is:[["apple",1],["banana",2],["orange",3]] but the pie is not working.
Anyone have any idea?
<script type="text/javascript">
$(document).ready(function() {
$('table.display').dataTable({
"paging": false,
"info": false
});
$('li').click(function(){
var cid = $(this).attr("id");
$.ajax({
type: "POST",
url: 'data.php',
data:{ cid:cid },
success:function(reponse){
alert(reponse)
/*options.series[0].data = reponse;
chart = new Highcharts.Chart(options);*/
}
});
var options = {
chart: {
renderTo: 'pie',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Web Sales & Marketing Efforts'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage}%</b>',
percentageDecimals: 1,
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ Highcharts.numberFormat(this.percentage, 1); +' %';
}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ Highcharts.numberFormat(this.percentage, 1); +' %';
}
}
}
},
series: [{
type: 'pie',
dataType: 'json',
name: 'Browser share',
data: []
}]
}
$.getJSON("data.php", function(json) {
options.series[0].data = json;
chart = new Highcharts.Chart(options);
});
});
});
</script>
data.php
<?php
require_once("../connectDB.php");
$cid = isset($_POST["cid"]) ? $_POST["cid"] : "";
$result = $db->prepare("SELECT stu_info.reference FROM stu_info , user_student WHERE stu_info.sid = user_student.sid and user_student.cid = :cid");
$result ->execute(array(':cid' => $cid,));
$one = 0; $two = 0; $three = 0;
while($r = $result -> fetch()) {
if($r['reference'] === "apple")
$one = $one+1;
else
if($r['reference'] === "banana")
$two = $two+1;
else
if($r['reference'] === "orange")
$three = $three+1;
}
$ra = array($one,$three,$two);
$rb = array(apple,banana,orange);
$rows = array();
for($i=0 ; $i<=2 ; $i=$i+1)
{
$row[0] = $rb[$i];
$row[1] = $ra[$i];
array_push($rows,$row);
}
print json_encode($rows, JSON_NUMERIC_CHECK);
?>

You cant just write $cid in the query text. You have to build the string:
"SELECT stu_info.reference FROM stu_info , user_student WHERE stu_info.sid = user_student.sid and user_student.cid = " . $cid
Edit: It looks like the concatenation operator in php is . Rather than +

Related

Highcharts unable to draw with ajax data

Highcharts unable to draw with ajax data it works with static data comes in ajax response.
is there a need to redraw or something, I tried but didn't work.
i have tried window load event as well and also tried with json stringify.
=====================view =================================
<script type="text/javascript"> $(document).ready(function () {
/****************** Get ur parameters *********************************/
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
/***************************************************/
var tm_id = getUrlVars()["tm_id"];
var trunk_id = getUrlVars()["trunk_id"];
var chart = $('#container').highcharts();
$.ajax({
url: "completedcallgraph?tenant_id=" + tm_id + "&trunk_id=" + trunk_id,
method: "GET",
success: function (result) {
var resultObj = JSON.parse(result);
setTimeout(function(){drawHighchart(resultObj.currentcalls,resultObj.inserted_at,resultObj.maxcallpath);
}, 1000);
}
});
function drawHighchart(currentcalls,inserted_at,maxcallpath){
$('#container').highcharts({
chart: {
type: 'line',
zoomType: 'xy',
panning: true,
panKey: 'shift'
},
title: {
text: 'CallPath Current Utilization',
x: -20 //center
},
xAxis: {
title: {
text: 'Time'
},
categories: [inserted_at]
},
yAxis: {
title: {
text: 'CallDetails'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
valueSuffix: '°C'
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0,
showInLegend: false
},
series:[{name: 'tioc_total_current_calls',data: [currentcalls]},{name: 'tioc_max_call_paths',data: [maxcallpath],dashStyle: 'shortdot',color: 'red'}]
});
}
});
</script>
================ Controller =======================
public function actionCompletedcallgraph($tenant_id, $trunk_id)
{
$completedCallCount = (new Query())
->from('ntc.callpath_utilizationreport_data')
->where(['tm_id' => $tenant_id])->andWhere(['trunk_id' => $trunk_id])
->all();
// Completed Calls Code
$callDetails = '';
$inserted_at = '';
$tioc_max_call_paths = '';
$tioc_total_current_calls = '';
$tioc_inbound_calls = '';
$tioc_outbound_calls = '';
foreach ($completedCallCount as $key => $value) {
$tioc_max_call_paths .= $value['tioc_max_call_paths'].',';
$tioc_total_current_calls .= $value['tioc_total_current_calls'].',';
$tioc_inbound_calls .= $value['tioc_inbound_calls'].',';
$tioc_outbound_calls .= $value['tioc_outbound_calls'].',';
$inserted_at .= $value['inserted_at'] * 1000 . ',';
}
$inserted = rtrim($inserted_at,',') ;
$maxcallpath =rtrim($tioc_max_call_paths,',') ;
$currentcalls =rtrim($tioc_total_current_calls,',') ;
return $result = json_encode(['currentcalls' => $currentcalls,'maxcallpath' => $maxcallpath, 'inserted_at' => $inserted]);
}

Cannot Remove Credits (Link) in HighChart's PieChar

I tried enable:false
but i cannot remove highchart's link from my chart (pie).
I got bit confused
This is my Javascript code.
<script language="JavaScript">
$(document).ready(function() {
var chart = {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
credits: false ///<= HERE I TRIED IT LAST
};
var title = {
text: ''
};
var tooltip = {
pointFormat: '{series.name}: <b>{point.y:.1f} Coupon(s)</b>'
};
var plotOptions =
{
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true,
borderWidth: 0
},
series: {
states: {
hover: {
halo:
{
size: 0
}
}
}
},
};
var series= [{
type: 'pie',
name: 'Source',
data: [
<?php
for($x=0; $x<sizeof($data); $x++)
{
echo $data[$x];
echo ",";
}
?>
]
}];
var json = {};
json.chart = chart;
json.title = title;
json.tooltip = tooltip;
json.series = series;
json.plotOptions = plotOptions;
$('#container').highcharts(json);
});
</script>
I tried to put this code at multiple positions. But it is showing no result.
Thanks in advance
var license = {
enabled: false
};
then at bottom:
json.credits = license;
previously asked and answered here
If you are using the free version, you CAN remove the attribution link, but if you are using free code the honour system is there so at least you can leave a "hat tip" to the developers as a thank you for saving you time.

How to show percentage and number in pie chart?

I am working on pie chart to show my data. I can work fine with it just now to show only percentage. But what I wish to do is to show both percentage and number.
JS:
$(function() {
var data = [];
#if(count($data) > 0)
data = <?php echo json_encode($data)?>;
#endif
var options = {
series: {
pie: {
show: true
}
},
legend: {
show: false
},
grid: {
hoverable: false,
clickable: true
},
colors: ["#94BEE0", "#D9DD81", "#E67A77","#747ddd","#669aaa","#aa7765"],
tooltip: true,
tooltipOpts: {
defaultTheme: false
}
};
$.plot($("#pie-chart #pie-chartContainer"), data, options);
};
My data result
$total_amount = array_sum($interest_income);
foreach($interest_income as $key => $inc){
if($inc > 0){
$per_value = ($inc * 100)/$total_amount;
$data[] = [
'label'=> $label[$key],
'data'=> $per_value
];
}
}
Your PHP is generating percentages, but you'll need to change it to generate the raw numbers (Flot can work out the percentages automatically):
foreach($interest_income as $key => $inc){
if($inc > 0){
$data[] = [
'label'=> $label[$key],
'data'=> $inc
];
}
}
Then, in your JavaScript, use a formatter for your labels like this:
formatter: function (label, series) {
var labelName = label;
var labelNumber = series.data[0][1];
var labelPercent = series.percent;
var labelContent = label + '<br/>' + labelNumber + ' (' + labelPercent + '%)';
return '<div style="font-size:8pt;text-align:center;padding:2px;color:white;">' + labelContent + '</div>';
},
You would include this in your options, like this:
var options = {
series: {
pie: {
show: true,
label: {
formatter: function (label, series) {
var labelName = label;
var labelNumber = series.data[0][1];
var labelPercent = series.percent;
var labelContent = label + '<br/>' + labelNumber + ' (' + labelPercent + '%)';
return '<div style="font-size:8pt;text-align:center;padding:2px;color:white;">' + labelContent + '</div>';
},
}
}
},
legend: {
show: false
},
grid: {
hoverable: false,
clickable: true
},
colors: ["#94BEE0", "#D9DD81", "#E67A77","#747ddd","#669aaa","#aa7765"],
tooltip: true,
tooltipOpts: {
defaultTheme: false
}
};
JSFiddle: http://jsfiddle.net/LvLfcdur/

Drawing mysql data with highcharts

I'm trying to plot data from a mysql table on document load with highcharts:
the html looks like that:
function FetchData(){
//alert("Fetching");
$.ajax({
url: 'php/reports/fetch_data.php',
success: function(data) {
dataTemp = [];
for(i=0;i<data.length;i++){
dataTemp.push(data[i][0]); // '1' index for getting that temp value. '0' for date.
}
c_temperature.series[0].data = dataTemp;
for(i=0;i<data.length;i++){
dataTemp.push(data[i][1]); // '1' index for getting that temp value. '0' for date.
}
c_temperature.series[1].data = dataTemp;
}
});
function DrawCharts(){
c_temperature = new Highcharts.Chart({
chart: {
renderTo: 'dashboard',
defaultSeriesType: 'spline',
},
title: {
text: 'Temperatur'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 10
}
},
legend:{
enabled: false
},
credits:{
enabled: false
},
series: [{
name: 'Temperatur',
data: []
}]
});
$(document).ready(function() {
DrawCharts();
FetchDevices();
FetchData();
});
<body>
<div id="dashboard">
</div>
<div class="clear"></div>
</body>
And the php I call looks like that:
try {
$con = new PDO("mysql:host=$servername; dbname=$dbname", $username, $password);#
echo 'Connected</br>';
$sql = "select ZEIT,FEUCHTE,TEMPERATUR,LUX,PITCH from ".$mac.
" order by ID";
foreach($con - > query($sql) as $row) {
$x = $row['ZEIT'];
/*$x = mktime()*1000;*/
$y_h = (float) $row['FEUCHTE'];
/*$y_t=(float)$row['TEMPERATUR'];
$y_l=(float)$row['LUX'];
$y_a=(float)$row['PITCH'];*/
$ret = array($x, $y_h, /*$y_t,$y_l,$y_a,$mac*/ );
echo json_encode($ret);
}
$con = null;
}
The php code successfully returns data.
But I dont see a graph and debugging with the browser console does not give a clue either. Any suggestions what I'm doing wrong?
Beste Regards
You want to use c_temperature.series[0].setData(dataTemp, true); and c_temperature.series[1].setData(dataTemp, true);. By setting the data, you're not actually telling highcharts to redraw the chart, so nothing is happening when you update the data.
I think it has to do with the order in wich you do your operations: firstly you create the chart and then you make the ajax call to fetch the data, but you are not updating the chart.
Try to move the chart creation inside the ajax success callback: first populate the series array with the data received from PHP, then construct the chart passing the serie array as a option; like this:
success: function(data) {
var data_series = [];
/* here populate the data_series array from your PHP results */
new Highcharts.Chart({
/* here other options... */
series: data_series
});
So this is what I'm doing now:
function FetchData(){
$.ajax({
type: "POST",
url: 'php/reports/fetch_data.php',
data: "",
dataType: 'json',
success: function(data) {
var points = data;
c_temperature = new Highcharts.Chart({
chart: {
renderTo: 'dashboard',
defaultSeriesType: 'spline',
},
title: {
text: 'Temperatur'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: '°C',
margin: 10
}
},
legend:{
enabled: false
},
credits:{
enabled: false
},
series: points
});
/*dataTemp = [];
for(i=0;i<data.length;i++){
dataTemp.push(data[0][i]);
}
c_temperature.series[0].setData(dataTemp, true);
for(i=0;i<data.length;i++){
dataTemp.push(data[1][i]);
}
c_temperature.series[1].setData(dataTemp, true);*/
}
});
}
Result: it is showing the graph but still no plot.
The php return has been changed to this:
try {
$con = new PDO("mysql:host=$servername; dbname=$dbname" ,$username, $password);
$sql = "select ZEIT,FEUCHTE,TEMPERATUR,LUX,PITCH from ".$mac." where ID>'60080' order by ID";
$x = array();
$y_h = array();
foreach ($con->query($sql) as $row)
{
$x[]=$row['ZEIT'];
$y_h[]=(float)$row['FEUCHTE'];
$ret = array($x,$y_h);
}
echo json_encode($ret);
$con = null;
}

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 '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';
}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ 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);
?>
<input type='hidden' id='graphContentdata' value="<?php echo $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???
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]]");

Categories