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]);
}
Related
With the Highcharts value-in-legend plugin http://www.highcharts.com/plugin-registry/single/10/Value-In-Legend, I have been able to kind of implement a sort of multiple series total, but I do not understand how to get a total for a clicked y-axis point.
For example when I click, one day I will get the 3 separate series numbers, but I would like to get a total somehow as well, but I only know the y points on load and the visible y-points on redraw. I think the difficulty is getting the total of the 3 series points versus getting the individual point's value.
$(function() {
// Start the standard Highcharts setup
var seriesOptions = [],
yAxisOptions = [],
seriesCounter = 0,
names = ['MSFT', 'AAPL', 'GOOG'],
colors = Highcharts.getOptions().colors;
$.each(names, function(i, name) {
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=' + name.toLowerCase() + '-c.json&callback=?', function(data) {
seriesOptions[i] = {
name: name,
data: data
};
// As we're loading the data asynchronously, we don't know what order it will arrive. So
// we keep a counter and create the chart when all the data is loaded.
seriesCounter++;
if(seriesCounter == names.length) {
createChart();
}
});
});
// create the chart when all data is loaded
function createChart() {
$('#container').highcharts('StockChart', {
chart: {
events: {
load: function(event) {
console.log('load');
var total = 0;
for(var i = 0, len = this.series[0].yData.length; i < len; i++) {
total += this.series[0].yData[i];
}
totalText_posts = this.renderer.text('Total: ' + total, this.plotLeft, this.plotTop - 35).attr({
zIndex: 5
}).add()
},
redraw: function(chart) {
console.log('redraw');
console.log(totalText_posts);
var total = 0;
for(var i = 0, len = this.series[0].yData.length; i < len; i++) {
if(this.series[0].points[i] && this.series[0].points[i].visible) total += this.series[0].yData[i];
}
totalText_posts.element.innerHTML = 'Total: ' + total;
}
}
},
rangeSelector: {
selected: 4
},
yAxis: {
labels: {
formatter: function() {
return(this.value > 0 ? '+' : '') + this.value + '%';
}
},
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},
legend: {
enabled: true,
floating: true,
align: 'left',
verticalAlign: 'top',
y: 35,
labelFormat: '<span style="color:{color}">{name}</span>: <b>{point.y:.2f} USD</b> ({point.change:.2f}%)<br/>',
borderWidth: 0
},
plotOptions: {
series: {
compare: 'percent',
cursor: 'pointer',
point: {
events: {
click: function () {
alert('Category: ' + this.category + ', value: ' + this.y);
}
}
}
}
},
series: seriesOptions
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/stock/highstock.src.js"></script>
<script src="http://code.highcharts.com/stock/modules/exporting.js"></script>
<script src="https://rawgithub.com/highslide-software/value-in-legend/master/value-in-legend.js"></script>
<div id="container" style="height: 400px; min-width: 500px"></div>
I was able to find out a way to put the total result as a title in a multi series by reading the source code for the Highcharts value-in-legend plugin https://rawgithub.com/highslide-software/value-in-legend/master/value-in-legend.js.
$(function () {
var seriesOptions_likes = [],
seriesCounter_likes = 0,
names_likes = ['MSFT', 'AAPL', 'GOOG'],
totalText_likes = 0;
/**
* Create the chart when all data is loaded
* #returns {undefined}
*/
function createLikesChart() {
Highcharts.stockChart('container_likes', {
chart: {
},
rangeSelector: {
selected: 4
},
title: {
text: 'Total Results: '
},
yAxis: {
labels: {
formatter: function () {
return (this.value > 0 ? ' + ' : '') + this.value + '%';
}
},
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},
plotOptions: {
series: {
compare: 'percent',
showInNavigator: true
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2,
split: true
},
series: seriesOptions_likes,
legend: {
enabled: true,
floating: true,
align: 'left',
verticalAlign: 'top',
y: 65,
borderWidth: 0
},
});
}
$.each(names_likes, function (i, name) {
$.getJSON('https://www.highcharts.com/samples/data/jsonp.php?filename=' + name.toLowerCase() + '-c.json&callback=?', function (data) {
seriesOptions_likes[i] = {
name: name,
data: data
};
// As we're loading the data asynchronously, we don't know what order it will arrive. So
// we keep a counter and create the chart when all the data is loaded.
seriesCounter_likes += 1;
if (seriesCounter_likes === names_likes.length) {
createLikesChart();
}
});
});
});
(function (H) {
H.Series.prototype.point = {}; // The active point
H.Chart.prototype.callbacks.push(function (chart) {
$(chart.container).bind('mousemove', function () {
var legendOptions = chart.legend.options,
hoverPoints = chart.hoverPoints,
total = 0;
if (!hoverPoints && chart.hoverPoint) {
hoverPoints = [chart.hoverPoint];
}
if (hoverPoints) {
var total = 0,
ctr = 0;
H.each(hoverPoints, function (point) {
point.series.point = point;
total += point.y;
});
H.each(chart.legend.allItems, function (item) {
item.legendItem.attr({
text: legendOptions.labelFormat ?
H.format(legendOptions.labelFormat, item) :
legendOptions.labelFormatter.call(item)
});
});
chart.legend.render();
chart.title.update({ text: 'Total Results: ' + total.toFixed(2) });
}
});
});
// Hide the tooltip but allow the crosshair
H.Tooltip.prototype.defaultFormatter = function () { return false; };
}(Highcharts));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<div id="container_likes" style="height: 400px; min-width: 600px"></div>
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;
}
I have data being put on an api every 30 seconds on a backend. On the frontend I am using highcharts to visualize the data and a setInterval setup to retrieve the new data every 30 seconds. My problem is that on that setInterval, the line graph disappears or does not draw to the next new dot. Does anyone now why this is?
fiddle: http://jsfiddle.net/b8tf281n/3/
code:
chart1 = {
yAxisMin: 40,
yAxisMax: 100
};
// empty objects for our data and to create chart
seriesData = [];
BPM = [];
time1 = [];
// console.log(chart1.data.series);
$(function () {
$(document).ready(function () {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var url = 'http://msbandhealth.azurewebsites.net/odata/PulsesAPI/';
$.ajax({
url: url,
dataType: 'json',
context: seriesData,
success: function (data) {
// structure our data
for (var i = 0; i < data.value.length; i++) {
bpm = data.value[i].BPM;
time = data.value[i].Time;
BPM.push({
x: moment(time),
y: bpm
});
// console.log(BPM);
time1.push(time);
}
console.log((new Date).getTime());
console.log(moment(time, "DD.MM.YYYY hh:mm:ss"));
console.log(BPM);
console.log(BPM[BPM.length - 1]);
// console.log(seriesData);
// set our data series and create new chart
chart1.data.series[0].data = BPM;
chart = new Highcharts.Chart(chart1.data);
$('#container').css({
height: '400px'
});
// console.log(sortedBPM);
// console.log(time1);
}
});
// give highcharts something to render to
var container = document.getElementById("container");
chart1.data = {
chart: {
renderTo: container,
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function () {
setInterval(function () {
// find last data points
var test = BPM[BPM.length - 1];
var x = (new Date).getTime(),
y = test.y;
console.log(x);
shift = chart.series[0].data.length < 30;
chart.series[0].addPoint([x, y], true, true);
},
30000);
}
}
},
title: {
text: 'Microsoft Band: Real Time Pulse Analysis'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
dateTimeLabelFormats: {
},
},
yAxis: {
min: chart1.yAxisMin,
max: chart1.yAxisMax,
title: {
text: 'Heart Rate'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' + Highcharts.dateFormat('%H:%M:%S', this.x) + '<br/>' + Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Beats Per Minute',
data: []
}]
};
});
});
Your test.y is the problem. It returns undefined after one interval. Somehow BPM is changing in it's structure - changing each object from {x,y} to [0,1] - therefore I used:
y = (test.y !== undefined)? test.y : test[1];
to either get the previous structure or the new. I also set the interval to 3 seconds for you to see the difference easier. Here's the DEMO.
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 +
I am new to Highcharts, Sharepoint and JS. What I need to do is make each bar link to a SharePoint view
This code gets the data
IWSChartBuilder.EngagementsSegmentChart = function () {
var load = function () {
var year = new Date().getFullYear();
//Variable to hold counts
var countArray = [];
$.when(
//Consulting Engagements List
IWSChartBuilder.RESTQuery.execute("valid REST query")
).done(
function (engagements1) {
var dataArray = [];
var countArray = [];
//Get data from Consulting Engagements list
var results = engagements1.d.results;
for (var i = 0; i < results.length; i++) {
for (var i = 0; i < results.length; i++) {
dataArray.push(results[i].Segment);
}
}
var baseUrl = "valid url";
countArray = IWSChartBuilder.Utilities.buildCategoryCountsWithLink(countArray, dataArray, baseUrl);
//Put data into format for stacked bar chart
var seriesData = [];
var xCategories = [];
var links = [];
for (var i = 0; i < countArray.length; i++) {
xCategories.push(countArray[i].name);
seriesData.push(countArray[i].y);
links.push(countArray[i].url);
}
//Build Chart
IWSChartBuilder.Utilities.loadColumnChartWithLink(links, xCategories, seriesData, "#engagementSegmentChart", "Engagements by Segment", "Total Projects");
}
).fail(
function (engagements1) {
$("#engagementSegmentChart").html("<strong>An error has occurred.</strong>");
}
);
};
return {
load: load
}
}();
//code to display chart
loadColumnChartWithLink = function (xCategories, seriesData, divId, chartTitle, yAxisTitle) {
//Build Column Chart
$(divId).highcharts({
chart: {
type: 'column'
},
credits: {
enabled: false
},
title: {
text: chartTitle
},
xAxis: {
categories: xCategories,
allowDecimals: false,
labels: {
rotation: -45,
align: 'right'
}
},
yAxis: {
min: 0,
allowDecimals: false,
title: {
text: yAxisTitle
}
},
legend: {
enabled: false
},
plotOptions: {
bar: {
dataLabels: {
enabled: false
}
},
series: {
cursor: 'pointer',
point: {
events: {
click: function() {
location.href = this.options.url;
}
}
}
}
},
series: [{
name: yAxisTitle,
data: seriesData
}]
});
},
Any help is greatly appreciated
Mark
You need to adapt your data to create objects as points, like in the example:
{y:10,url:'http://google.com'}
and then catch click event on serie's point.
http://jsfiddle.net/2tL5T/