Dynamic column based highcharts feeding data with jquery and php - php

I am trying to build column based highcharts, and here is my code in jquery:
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
credits: {
enabled: false
},
title: {
text: 'PCP Histogram',
x: -20
},
xAxis: {
categories: [{}]
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
tooltip: {
formatter: function() {
var s = '<b>'+ this.x +'</b>';
$.each(this.points, function(i, point) {
s += '<br/>'+point.series.name+': '+point.y;
});
return s;
},
shared: true
},
series: [{},{}]
};
$.ajax({
url: "file.php",
type: "post",
dataType: "json",
success: function(data){
options.xAxis.categories = data.categories;
options.series[0].name = 'Avg1';
options.series[0].data = data.avg1;
options.series[1].name = 'Avg2';
options.series[1].data = data.avg2;
var chart = new Highcharts.Chart(options);
And I getting the data from file php like this:
file.php
$graph_data = array('categories'=>$categories, 'avg1'=>$avg, 'avg2'=>$avg);
print json_encode($graph_data, JSON_NUMERIC_CHECK);
It is working fine with two columns per category,
What I want now is: the graph_data can have n number of avg datas,
so basically it will be n number of columns.
$graph_data = array('categories'=>$categories, 'avg1'=>$avg1, ... 'avgn'=>$avgn);
When I do it manually it works, but I will not know how many of them will be there, so I want the code to do i.
Any idea how I can do it?
Any help appreciated.

make an array of avg instead of having avg1, avg2 etc....
$graph_data = array('categories'=>$categories, 'avgs'=>$array_of_avgs)
then in javascript side
success: function(data){
options.xAxis.categories = data.categories;
for(var i in data.avgs){
options.series[i].name = 'Avg'+i;
options.series[i].data = data.avgs[i];
}
var chart = new Highcharts.Chart(options);
And everything will be fine

Related

How to show multiple highcharts on selection of few parameters and dynamically load JSON data using PHP page?

I have two parameters to load dynamic json data from mysql and visualise multiple line charts on page submit.
$.ajax({
url: 'get_pubmedid.php',
type: 'get',
data: {org: org, ptype: ptype, path: path,mirna: mirna},
dataType: 'json',
success:function(response) {
var len = response.length;
for( var i = 0; i<len; i++) {
pubmed = response[i]['name'];
cell=response[i]['cell'];
alert(cell+" "+pubmed+" "+len);
var cells=encodeURIComponent(cell);
var cname="charts"+(i+1);id=i+1;var pid=i+1;
var container = cname;
var func_name = cname;
func_name = function () {
Highcharts.chart(container, {
showhighcharts(org,ptype,path,mirna,cell,cells,pid,pubmed,cname,id);
}
}
func_name()
}
}
});
function showhighcharts(org,ptype,path,mirna,cell,cells,pid,pubmed,cname,id) {
$("#"+cname).html("Wait, Loading graph...");
var options = {
chart: {
type: 'line',
renderTo: cname
},
colors: ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4'],
credits: {
enabled: false
},
title: {
text: 'Temporal Viewer',
x: -20
},
xAxis: {categories:<?php //echo $_SESSION["cat"]; ?>,
offset:2,
title: {enabled: true,text: 'Time Point' }
},
tooltip: {
shared: true,
useHTML: true,
headerFormat: '<b>Time Point:{point.key}</b> <table style="width:200px;font-size:12px;font-weight:bold;">',
pointFormat: '<tr><td>Dosage:</td><td style="color: {series.color}">{series.name} </td></tr>' + '<tr><td>Fold Change:</td><td style="color: {series.color}">{point.y} </td></tr>',
footerFormat: '</table>',
enabled: true,
crosshairs: {
color: 'light gray',
dashStyle: 'longdash'
}
},
plotOptions: {
series: {
dashStyle: 'longdash'
},
line: {
dataLabels: {
enabled: true
},
enableMouseTracking: true
}
},
series: [{}]
};
$.ajax({
url: "jdatas.php?org="+org+"&ptype="+ptype+"&path="+path+"&mirna="+mirna+"&pid="+id+"&cell="+cell+"&pub="+pubmed,
data: 'show=impressions',
type:'get',
dataType: "json",
success: function(data){
var getSeries = data;
options.series = getSeries;
var chart1 = new Highcharts.Chart(options);
}
});
I want multiple graphs to be loaded on submit.
But its not showing any graph.

Ajax with HighCharts setData on Symfony 2

I have a problem on my HighCharts graph with JSON data. To explain a litle bit : I have a form, when I submit this form I send my data to my controller with Ajax, I treat them and I return the new array of data for my highcharts graph, but when I use setData function with my new array the graph disappear and the new data aren't displayed.
Here is my ajax function and my test to set the new data into my graph :
$('#gestion .l-gestion-content-form #form-add-informations .btn-validation').click(function(e) {
e.preventDefault();
var chart = $('#hightchart-graf').highcharts();
var dataActionForm = $('#form-add-informations').attr('action').split("/");
var url_ajax = Routing.generate('gestion_view', { dossier: dataActionForm[4], fille: dataActionForm[5] });
var formData = $('#form-add-informations').serializeArray();
$.ajax({
type: "POST",
dataType: 'json',
url: url_ajax,
data: formData,
success: function(msg)
{
console.log(msg['infosArray']);
var test = [ msg['infosArray'].join(',') ];
console.log(test);
console.log('---------------------------------------------');
console.log(msg.infosArray);
var test2 = msg.infosArray.join(',');
var test3 = test2.replace('"', '');
console.log(test2);
chart.series[0].setData( [ msg.infosArray.join(',') ] );
//[ {{ msg.infosArray | join(',') }} ]
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert('ERROR');
}
});
});
All my data are stored in the array named msg.infosArray or msg['infosArray'] and the first console.log return an array like this :
["[Date.UTC(2015,11,23),80.00]", "[Date.UTC(2015,11,23),89.00]", "[Date.UTC(2015,11,25),150.00]", "[Date.UTC(2015,11,28),45.00]", "[Date.UTC(2015,11,29),169.00]", "[Date.UTC(2015,11,29),189.00]", "[Date.UTC(2015,11,29),196.00]", "[Date.UTC(2015,11,29),200.00]", "[Date.UTC(2015,11,29),205.00]", "[Date.UTC(2015,11,30),210.00]", "[Date.UTC(2015,11,31),225.00]", "[Date.UTC(2016,0,1),250.00]", "[Date.UTC(2016,0,2),25.00]", "[Date.UTC(2016,0,3),259.00]", "[Date.UTC(2016,0,5),25.00]", "[Date.UTC(2016,0,6),250.00]", "[Date.UTC(2016,0,7),25.00]", "[Date.UTC(2016,0,8),250.00]", "[Date.UTC(2016,0,9),25.00]", "[Date.UTC(2016,0,10),250.00]", "[Date.UTC(2016,0,11),25.00]", "[Date.UTC(2016,0,12),250.00]", "[Date.UTC(2016,0,25),25.00]", "[Date.UTC(2016,0,26),250.00]"]
So I tried to escape " and ' or to join the array but nothing work. Somebody know how can I set the new data, or where I commited a fault ?
Maybe i got a bad response from my Controller ?
Thanks
You need to convert string of javascript code to array of javascript.
I wrote a demo version which converts string to javascript code. and draws chart as expected. Do not focus on the labels it's a dummy data.
JSFiddle Demo
$(function () {
var data = ["[Date.UTC(2015,11,23),80.00]", "[Date.UTC(2015,11,23),89.00]", "[Date.UTC(2015,11,25),150.00]", "[Date.UTC(2015,11,28),45.00]", "[Date.UTC(2015,11,29),169.00]", "[Date.UTC(2015,11,29),189.00]", "[Date.UTC(2015,11,29),196.00]", "[Date.UTC(2015,11,29),200.00]", "[Date.UTC(2015,11,29),205.00]", "[Date.UTC(2015,11,30),210.00]", "[Date.UTC(2015,11,31),225.00]", "[Date.UTC(2016,0,1),250.00]", "[Date.UTC(2016,0,2),25.00]", "[Date.UTC(2016,0,3),259.00]", "[Date.UTC(2016,0,5),25.00]", "[Date.UTC(2016,0,6),250.00]", "[Date.UTC(2016,0,7),25.00]", "[Date.UTC(2016,0,8),250.00]", "[Date.UTC(2016,0,9),25.00]", "[Date.UTC(2016,0,10),250.00]", "[Date.UTC(2016,0,11),25.00]", "[Date.UTC(2016,0,12),250.00]", "[Date.UTC(2016,0,25),25.00]", "[Date.UTC(2016,0,26),250.00]"];
//t = t.map(function(element){return eval(element);});
data = data.map(function (e) {
return eval(e);
});
data = data.map(function (e) {
return [(new Date(e[0])).toLocaleString(), e[1]]
});
var categories = data.map(function (e) {
return (new Date(e[0])).toLocaleString()
});
// t[0] = [date = new Date(t[0])];
$('#container').highcharts({
title: {
text: 'Monthly Average Temperature',
x: -20 //center
},
subtitle: {
text: 'Source: WorldClimate.com',
x: -20
},
xAxis: {
categories: categories
},
yAxis: {
title: {
text: 'Temperature (°C)'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
valueSuffix: '°C'
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: [{
name: 'Tokyo',
data: data
}]
});
});

dynamic auto update highcharts using ajax from mysql database [duplicate]

I m trying to figure it out that is it possible to make the json data fetched dynamically from a database with the help of php and mysql and can be plotted with highcharts that too dynamic auto updating? Any help would be appreciated.
following the code i have tried and is not working properly and want to implement to the the website for 10 lines.
<HTML>
<HEAD>
<TITLE>highchart example</TITLE>
<script type="text/javascript"src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script type="text/javascript">
var chart;
function requestData() {
$.ajax({
url: 'live-server-data.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is
// longer than 2
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData1, 1000);
},
cache: false,
});
}
function requestData1() {
$.ajax({
url: 'live-server-data.php',
success: function(point) {
var series2 = chart.series[1],
shift = series2.data.length > 20; // shift if the series is
// longer than 20
// add the point
chart.series[1].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false,
});
}
$(function () {
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis:
{
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: '',
margin: 80
}
},
series: [
{
name: 'Random data',
data: []
},
{
name: ' hahaha',
data: []
}
],
});
});
});
</script>
</HEAD>
<BODY>
<div id="container"
style="min-width: 728px; height: 400px; margin: 0 auto"></div>
</BODY>
</HTML>
*** the live-server-data.php is as followed:
<?php
// Set the JSON header
header("Content-type: text/json");
// The x value is the current JavaScript time, which is the Unix time multiplied
// by 1000.
$x = time() * 1000;
// The y value is a random number
$y = rand(48,52);
// Create a PHP array and echo it as JSON
$ret = array($x, $y);
echo json_encode($ret);
?>
You can try with
var options = {
chart: {
renderTo: 'chart',
},
credits: {
enabled: false
},
title: {
text: 'Impression/Click Overview',
x: -20
},
xAxis: {
categories: [{}]
},
tooltip: {
formatter: function() {
var s = '<b>'+ this.x +'</b>';
$.each(this.points, function(i, point) {
s += '<br/>'+point.series.name+': '+point.y;
});
return s;
},
shared: true
},
series: [{},{}]
};
$.ajax({
url: "json.php",
data: 'show=impression',
type:'post',
dataType: "json",
success: function(data){
options.xAxis.categories = data.categories;
options.series[0].name = 'Impression';
options.series[0].data = data.impression;
options.series[1].name = 'Click';
options.series[1].data = data.clicks;
var chart = new Highcharts.Chart(options);
}
});
The highcharts website has some useful articles about working with dynamic data. That is probably the best place to start.
http://www.highcharts.com/docs/working-with-data/preprocessing-live-data
http://www.highcharts.com/docs/working-with-data/preprocessing-data-from-a-database
Try something out, and if you have trouble, come back here with a more specific question showing what you have tried. As it stands, your question is too broad, and will probably get closed.
An ajax request for updating data looks something like:
function requestData() {
$.ajax({
url: 'live-server-data.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is // longer than 20
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}

How can I convert datetime stamp in jQuery of a Highchart to get the correct format in json?

To start with I must confess I have not so good knowledge of jQuery and Json.
Basically my json encode reads like this ["2013-06-18 09:42:30",6.21],["2013-06-18 09:44:30",6.57],["2013-06-18 10:01:49",6.61],......these are the results of battery voltage in given date and time which keeps updating. There are hundreds of records.
I know this time stamp is not valid while plotting the graph so Yesterday I was trying to tweak the jQuery in jSfiddle to get result and convert it into a chart.
While working in Jsfiddle it said my code is fine but I am getting a blank container area.
Can anyone please guide me on how to convert the datetime stamp in UTC so that a graph can be plotted.
The jQuery which I was tweaking looks like this:
var chart;
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: requestData
}},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
month: '%e. %b',
year: '%b'
}
},
yAxis: {
title: {
text: 'Battery Voltage'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
Highcharts.dateFormat('%a %d %b %H:%M:%S', this.x) +' : '+ this.y +" V";
}
},
series: [{
name: 'Battery Volatge',
data: []
}]
});
function requestData() {
$.ajax({
url: 'data.php',
datatype: "json",
success: function(data) {
alert(data);
chart.series[0].setData(data);
},
cache: false
});
}
and my PHP looks like this:
<?php
header("Content-type: text/json");
$dbc = mysql_connect('xxxxx','xxxxx','xxxxx') or die(mysql_error());
mysql_select_db('xxxxx',$dbc) or die(mysql_error());
$result = mysql_query("SELECT COUNT(*) AS count FROM Station_State");
$row = mysql_fetch_array($result,MYSQL_ASSOC);
$SQL = "SELECT ss_Stamp,ss_BatteryStatus FROM Station_State WHERE Station_State_Index > 371298 AND ss_Station_idx = 34 ORDER BY ss_Stamp";
$result = mysql_query( $SQL ) or die("Couldn?t execute query.".mysql_error());
$i=0;
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$row[ss_BatteryStatus] = (float) $row[ss_BatteryStatus];
$rows[$i]=array($row[ss_Stamp],$row[ss_BatteryStatus]);
$i++;
}
echo json_encode($rows);
?>
It is probably a basic question but I am still learning so any advice will be appreciated. Do let me know if you need any more information or anything I mentioned sounds vague.
Thanks
You can simple preprocess your data. Before setting data loop through all points, and convert that string to timestamp, for example:
for (var i = 0; i < data.length; i++ ){
data[i][0] = new Date(data[i][0]).getTime();
}
Posting Code which works perfectly. The only problem is the a window pops up with encoded data.
jQuery code:
$(function () {
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var chart;
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
borderwidth: 0,
events: {
load: requestData
}},
title: {
text: 'Battery Graph'
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
month: '%e. %b',
year: '%b'
}
},
yAxis: {
title: {
text: 'Battery Performance Voltage'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
Highcharts.dateFormat('%a %d %b %H:%M:%S', this.x) +' : '+ this.y +" V";
}
},
series: [{
showInLegend: false,
name: 'Time vs Volatge',
data: []
}]
});
function requestData() {
$.ajax({
url: 'bdata.php',
datatype: "json",
success: function(data) {
alert(data);
for (var i = 0; i < data.length; i++ ){
data[i][0] = new Date(data[i][0]).getTime();
}
chart.series[0].setData(data);
},
cache: false
});
};
});
});
My PHP code looks like this:
<?php
header("Content-type: text/json");
$dbc = mysql_connect('xxxx','xxxx','xxxx') or die(mysql_error());
mysql_select_db('xxxx',$dbc) or die(mysql_error());
$result = mysql_query("SELECT COUNT(*) AS count FROM xxxx");
$row = mysql_fetch_array($result,MYSQL_ASSOC);
$SQL = "SELECT ss_Stamp,ss_BatteryStatus FROM Station_State WHERE Station_State_Index > 377708 AND ss_Station_idx = 34 ORDER BY ss_Stamp";
$result = mysql_query( $SQL ) or die("Couldn?t execute query.".mysql_error());
$i=0;
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$row[ss_BatteryStatus] = (float) $row[ss_BatteryStatus];
$rows[$i]=array($row[ss_Stamp],$row[ss_BatteryStatus]);
$i++;
}
echo json_encode($rows);
?>
Thank you Pawel. You have been great help.

Highcharts won't show line through my dots

This is my full code:
$(document).ready(function()
{
var options =
{
chart: { renderTo: 'zb' },
title: { text: 'Test' },
tooltip:
{
enabled: true,
formatter: function()
{
return '<b>' + this.x + ' ' + this.series.name + '</b><br/>' + this.y;
}
},
xAxis: { categories: [] },
yAxis: { title: { text: 'Visits Num' } },
series: [],
plotOptions:{ line: { lineWidth : 2 } }
};
var tpo;
$.ajax({url: 'utils/request2.php', success: function(data)
{
var lines = data.split('\n');
var series =
{
type: 'line',
name: 'Visits',
data: [],
marker: { enabled: true, radius : 3 }
};
var cats = [];
$.each(lines, function(lineNo, line)
{
var line_data = line.split(',');
series.data.push(parseInt(line_data[1]));
});
options.series.push(series);
var chart = new Highcharts.Chart(options);
}});
});
It calls to the request2.php file that have data (saved in UTF8 without BOM if it matters) separated with comma, 2 values per row
When I'm showing the data without the parseInt it's showing the line, but the numbers are wrong because it's string - like showing 1500 as 20
Anyone have an idea why?
Thanks alot.

Categories