Want to fetch mysql Field record in highchart tooltip - javascript

Here I am using highchart with codeigniter. I got highchart record with graph but I want record comes from mysql database field of "zreadactivity" in tooltip. I could not get proper name in tooltip for "zreadactivity" as it contains record. So, I just want to know that where I am stuck?
Here is my code:
Controller:
public function branchwiseactivityavg()
{
$data = $this->Data->branch_wise_activities();
$category = array();
$category['name'] = 'EndDate';
$series1 = array();
$series1['name'] = 'TotalValue';
$series2 = array();
$series2['name'] = 'zreadactivity';
foreach ($data as $row)
{
$category['data'][] = $row->EndDate;
$series1['data'][] = $row->TotalValue;
$series2['data'][] = $row->zreadactivity;
}
$result = array();
array_push($result,$category);
array_push($result,$series1);
array_push($result,$series2);
print json_encode($result, JSON_NUMERIC_CHECK);
}
Javascript:
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container5',
type: 'column',
marginRight: 130,
marginBottom: 25,
zoomType: 'x'
},
title: {
text: 'Branch wise activities Last 30 Days',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories : []
},
yAxis: {
title: {
text: 'TotalValue'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip:
{
formatter: function() { return ' ' +
'EndDate: ' + this.x + '<br />' +
'TotalValue: ' + this.y + '<br />' +
'zreadactivity: ' + this.series.name;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: []
};
$.getJSON("branchwiseactivityavg", function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
chart = new Highcharts.Chart(options);
});
});
</script>
zreadactivity table:
zreadacivity
---------------
Refund
Exchange
Voids
Cancel
Discount
Price Overwrite

One way is to create JSON where for series' data each point is defined as an array like:
[value_from_TotalValue, value_from_zreadactivity]
and set keys for series like:
series: [{keys: ['y','zreadactivity']}]
and in tooltip's formatter use this.point.zreadactivity to access zreadactivity.
Other option is to build this structure for series in JavaScript after getting JSON data.
Example with keys: http://jsfiddle.net/yhx2dp2g/
Example without keys: http://jsfiddle.net/yhx2dp2g/1/

Related

Highcharts not showing string value

I'm trying to add localstorage values into highchart series but it doesn't work.
When i print the "newString" value on the console and replace the value for "newString" at the code it works but it doesn't when I use var newString.
Here is the code:
$(document).ready(function () {
var archive,
j = "",
keys = Object.keys(localStorage),
x = keys.length;
var i = 0;
while (i < x) {
archive = JSON.parse(localStorage.getItem(keys[i]));
j += "{ name: " + keys[i] + ", data: [" + archive.username + ", " + archive.email + ", " + archive.password + "]},";
i++;
}
var newString = j.substr(0, j.length - 1);
console.log('newString: ', newString);
Highcharts.chart('container', {
title: {
text: 'Datos ingresados'
},
subtitle: {
text: 'Localstorage'
},
yAxis: {
title: {
text: 'Datos ingresados'
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
plotOptions: {
series: {
label: {
connectorAllowed: false
},
pointStart: 2017
}
},
series: [
newString
],
responsive: {
rules: [{
condition: {
maxWidth: 500
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom'
}
}
}]
}
});
});
This is what console.log shows:
{ name: 2, data: [12345, 23456, 34567]},{ name: 3, data: [23456, 34567, 45678]},{ name: 4, data: [34567, 45678, 56789]},{ name: 5, data: [45678, 56789, 67890]}
When I change the value of newString for that, it works properly.
Because in the second case, Highcharts see your data as a pure string. So, you need to parse your string.
But first of all, we should create valid json for parsing correctly:
var newString = "{ name: 2, data: [12345, 23456, 34567]}"; //bad json
var json = newString.replace(/(['"])?([a-zA-Z0-9]+)(['"])?:/g, '"$2":');
var goodJson = "[" + json + "]"; //valid json
Now we can create options for the Highcharts:
var options = {
chart: {
renderTo: 'container',
type: 'spline'
},
series: []
};
And push data to series as follows:
$.each(JSON.parse(goodJson), function(i, item) {
options.series.push({
name: item.name,
data: item.data
});
});
And finally initialize Highcharts:
var chart = new Highcharts.Chart(options);
See at Plunker

Dynamic updates with highcharts

I'm working with Highcharts and Highstock from a few weeks ago. Step by step, following the documentation and help online, I have builded some charts with interesting options. But now I have a question, and my skills with mysql and php are limited.
I get temperature values from a data base, every minute. I use a php file to connect to database, and then I build the chart. Now, I want to update the chart like in this example. But I can't find a right way. I was reading in Highcharts documentation, and Stackoverflow some answers, but I can't implement into my code.
I was working in 2 ways to implement the dynamic updates. The first one is:
<?php
function conectarBD(){
$server = "localhost";
$usuario = "user";
$pass = "password";
$BD = "databasename";
$conexion = mysqli_connect($server, $usuario, $pass, $BD);
if(!$conexion){
echo 'Ha sucedido un error inexperado en la conexion de la base de datos<br>';
}
return $conexion;
}
function desconectarBD($conexion){
$close = mysqli_close($conexion);
if(!$close){
echo 'Ha sucedido un error inexperado en la desconexion de la base de datos<br>';
}
return $close;
}
function getArraySQL($sql){
$conexion = conectarBD();
if(!$result = mysqli_query($conexion, $sql)) die();
$rawdata = array();
$i=0;
while($row = mysqli_fetch_array($result))
{
$rawdata[$i] = $row;
$i++;
}
desconectarBD($conexion);
return $rawdata;
}
$sql = "SELECT Probe1,Time from table2;";
$rawdata = getArraySQL($sql);
for($i=0;$i<count($rawdata);$i++){
$time = $rawdata[$i]["Time"];
$date = new DateTime($time);
$rawdata[$i]["Time"]=$date->getTimestamp()*1000;
}
?>
<HTML>
<BODY>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery.js"></script>
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container">
</div>
<script type='text/javascript'>
$(function () {
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var chart;
$('#container').highcharts({
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function () {
var series = this.series[0];
setInterval(function () {
<?php
for($i = 0 ;$i<count($rawdata);$i++){
?>
series.addPoint([<?php echo $rawdata[$i]["Time"];?>,<?php echo $rawdata[$i]["Probe1"];?>], true, true);
<?php } ?>
}, 90000);
}
}
},
title: {
text: 'Tunnel temperature'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'ºC'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
Highcharts.dateFormat('%d-%b %H:%M', this.x) +'<br/>'+
'<b>'+ Highcharts.numberFormat(this.y, 1) +'</b>';
}
},
legend: {
enabled: true
},
exporting: {
enabled: true
},
series: [{
name: 'Probe-1',
data: (function() {
var data = [];
<?php
for($i = 0 ;$i<count($rawdata);$i++){
?>
data.push([<?php echo $rawdata[$i]["Time"];?>,<?php echo $rawdata[$i]["Probe1"];?>]);
<?php } ?>
return data;
})()
}]
});
});
});
</script>
</html>
And this other way:
Connection to datatest2.php:
<?php
//convert the date values to Unix Timestamp
//Convert from 2017-02-28 19:30:01 to Tuesday, February 28 2017 19:30:01
$con = mysql_connect("localhost","username","password");
if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("databasename", $con);
$result = mysql_query("SELECT * FROM table2");
while ($row = mysql_fetch_array($result)) {
$uts=strtotime($row['Time']); //convertir a Unix Timestamp
$date=date("l, F j Y H:i:s",$uts);
//echo $valor3 . “\t” . $row[$valor2]. “\n”;
echo $date . "\t" . $row['Probe1'] . "\n";
}
mysql_close($con); ?>
And the php file for the chart:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Highstock & multiple</title>
<script src="https://code.jquery.com/jquery.js"></script>
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script type="text/javascript">
var chart;
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
defaultSeriesType: 'line',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Temperature Tunnel',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
rangeSelector: {
buttons: [
{
type: 'all',
text: 'all'
}, {
type: 'week',
count: 1,
text: '1w'
}, {
type: 'day',
count: 1,
text: '1d'
}, {
type: 'hour',
count: 18,
text: '18h'
}, {
type: 'hour',
count: 12,
text: '12h'
}, {
type: 'hour',
count: 6,
text: '6h'
}]
},
xAxis: {
type: 'datetime',
tickWidth: 0,
gridLineWidth: 1,
labels: {
align: 'center',
x: -3,
y: 20,
formatter: function() {
return Highcharts.dateFormat('%d-%b %H:%M', this.value);
}
}
},
yAxis: {
title: {
text: 'Celsius degrees'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return Highcharts.dateFormat('%d-%b %H:%M', this.x) +': <b>'+ this.y + '</b>';
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: [{
name: 'Probe1'
}]
}
jQuery.get('datatest2.php', null, function(tsv) {
var lines = [];
traffic = [];
try {
// split the data return into lines and parse them
tsv = tsv.split(/\n/g);
jQuery.each(tsv, function(i, line) {
line = line.split(/\t/);
date = Date.parse(line[0] +' UTC');
traffic.push([
date,
parseInt(line[1].replace(',', ''), 10)
]);
});
} catch (e) { }
options.series[0].data = traffic;
chart = Highcharts.stockChart (options);
setInterval(function() { tsv; }, 30000);
pollChart.series[0].setData(data);
});
});
</script>
</head>
<body>
<div id="container" style="width: 100%; height: 400px; margin: 0 auto"></div>
</body>
</html>
Can you help me to find and fix the mistake?
Thanks!
Alex.
Using a combination of your first example and the JSFiddle that you posted, I would try something like this:
chart: {
events: {
load: function () {
var series = this.series[0];
setInterval(function () {
<?php
for($i = 0 ;$i<count($rawdata);$i++){
?>
series.addPoint([<?php echo $rawdata[$i]["Time"];?>,<?php echo $rawdata[$i]["Probe1"];?>], true, true);
<?php } ?>
}, 1000);
}
}
}
Note that I have no idea whether your PHP code there is actually retrieving the data that you wanted, I have simply copied it from your example and made the assumption that that part of the code was ok.
The key here is the chart.events.load property, this takes a function that fires once the chart has finished loading. By calling setInterval here, your function will fire continuously after the chart finishes loading the first time.
By calling series.addPoint, your chart will redraw every time a new point is added, which I believe is what you want.
More information is available here about the load property.

HighCharts / Wordpress - How do I generate unique charts for ~4,800 posts?

Relatively new to HighCharts, PHP and JS but continuing to learn. I have searched extensively on the web but have not found anything that works so far.
I have a listing website that displays information on a variety of hospitals. As part of this offering, I am looking to show salary information unique to each hospital (~4,800) in HighCharts, using the WP post ID as the identifier.
I have a static chart showing across all hospitals as a placeholder right now but would like make this dynamic based on the individual hospital in question. I tried to use an Ajax POST command to push the right data without any luck thus far.
Any help or guidance would be greatly appreciated!
Code below:
JS Chart Display (Contained in a Widget)
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<!--
updatepage();
//--></script>
*** Function does not work when included ***
//var post_id = parseInt( ( document.body.className.match( /(?:^|\s)postid-([0-9]+)(?:\s|$)/ ) || [ 0, 0 ] )[1] ); // - JS to get post ID
var post_id = "1"; //Temporary post_id
jQuery(function($){
$('.section').click(function () {
jQuery.ajax({
url: http://www.rndeer.com/data.php,
type: 'POST',
data: post_id,
success:function(data) {
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
});
***********************
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'column',
marginRight: 130,
marginBottom: 25
},
colors: ['#0000FF', '#0066FF', '#3396d1'],
title: {
text: '<?php echo get_the_title();?>',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Salary ($ per / hour)'
},
plotLines: [{
value: 0,
width: 1,
color: '#3396d1'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': $'+ this.y+' per / hour';
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: []
}
$.getJSON("data.php", function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
options.series[1] = json[2];
options.series[2] = json[3];
chart = new Highcharts.Chart(options);
});
});
</script>
Data.PHP Script
<?php
$con = mysql_connect("localhost","Database_Name","Password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
//$post_id = $_POST['post_id']; - Attempt at getting posted data
$post_id = '1';
mysql_select_db("Database Name", $con);
$query = mysql_query("SELECT hospital, newgrad, median, high FROM salary_estimates WHERE id='".$post_id."'");
$category = array();
$category['name'] = 'Hospital';
$series1 = array();
$series1['name'] = 'New Grad';
$series2 = array();
$series2['name'] = 'Median';
$series3 = array();
$series3['name'] = 'High';
while($r = mysql_fetch_array($query)) {
$category['data'][] = $r['hospital'];
$series1['data'][] = $r['newgrad'];
$series2['data'][] = $r['median'];
$series3['data'][] = $r['high'];
}
$result = array();
array_push($result,$category);
array_push($result,$series1);
array_push($result,$series2);
array_push($result,$series3);
print json_encode($result, JSON_NUMERIC_CHECK);
mysql_close($con);
?>

Why does this Highcharts graph only show tooltip for the first and last nodes?

I'm just starting out with Highcharts and I'm having a little trouble showing a tooltip for each data item in my graph. At the moment, it just shows a tooltip for the first and last item.
var chart1; // globally available
$(document).ready(function () {
var options = {
chart: {
renderTo: 'AssessmentChart',
marginRight: 100,
marginBottom: 40
},
title: {
text: 'Assessment history',
x: -20 //center
},
subtitle: {
text: 'Assessment history for this patient',
x: -20 //center
},
xAxis: {
type: 'datetime'
},
yAxis: {
title: {
text: 'Score'
},
max: 72,
min: 0
},
tooltip: {
formatter: function() {
return '<b>'+ this.y +'</b>';
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: []
};
// Get the main assessment data...
var dlqiData = [], hdnDlqiData = $("#hdnDlqiData");
if (hdnDlqiData.length > 0) {
var dlqiDataJson = $.parseJSON(hdnDlqiData.val());
$.each(dlqiDataJson, function (i, item) {
dlqiData.push(
{
x: stringToUtcDate(item.dateCreated),
y: item.calculatedScore
}
);
});
options.series.push({
type: 'spline',
name: 'DLQI',
data: dlqiData
});
}
chart1 = new Highcharts.Chart(options);
function stringToUtcDate(datestring) {
var date = datestring.split('/');
return Date.UTC(parseInt(date[2], 10), parseInt(date[1], 10) - 1, parseInt(date[0], 10));
}
});​
I'm pulling data in from a hidden form field, so here's a Fiddle showing this in action: http://jsfiddle.net/gfyans/LjRGk/3/
Here's one of the official Fiddle's, http://jsfiddle.net/gh/get/jquery/1.7.2/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/line-basic/, and they manage it OK, but I can't see from that what I'm dong wrong/differently.
I know it'll be something insanely easy, but I can't see it. Can anyone point me in the right direction?
Thanks,
Greg.
You need to have your data in ascending date order if using a datetime x-axis.

Highcharts Displaying same data repeatedly

Thought I'd ask for a hand in this, am currently trying to code up a highcharts javascript file to display some data I have. I have been able to display the correct number of data sets, and on the correct graphs (they go into a time or proc graph) but I have an issue where ALL the graphs are using the same name & data, regardless of which graph they are on as well. Even though when i do an alert on where they are being assigned to their object arrays, they are all individual. Really unsure of what is happening.
where an Obj is:
{
name: SERIES_NAME,
data: SERIES_DATA,
}
The output graphs, instead of having the data as follows:
Graph Data: { Obj1, Obj2, Obj3...ObjN }, Showing multiple individual series.
I have:
Graph Data: { ObjN, ObjN, ObjN...ObjN },
They are all just ObjN. Even across the two graphs. All the data/names are the same.
Also all of this code is called from within a php $(document).ready(function())
function create_highchart(TIER,ARRAYS_STRING) {
var chart;
timestamp=document.getElementById("TIMESTAMP").value;
var graph_dir = "graphs/capsim/"+timestamp+"/";
var glue_outer = "___";
var glue_inner = ":#:";
var glue_csv="^";
var i = 0;
var j = 0;
var tier_names=[];
var WL_names = [];
var CSV_data=[];
var CSVs = [];
var CSV_det=[];
var out_arrays=[];
var time_ids = ['queue','util','arrival','thruput'];
out_arrays = ARRAYS_STRING.split(glue_outer);
tier_names = out_arrays[0].split(glue_inner);
WL_names = out_arrays[1].split(glue_inner);
CSVs = out_arrays[2].split(glue_inner);
CSV_det = out_arrays[3].split(glue_inner);
WL_num = WL_names.length;
tier_names.push('Overall System');
tier_max = tier_names.length;
curr_tier_name = tier_names[TIER];
while(i<CSVs.length){
CSV_data[i]=[];
data = CSVs[i].split(glue_csv);
CSV_data[i]=data;
i=i+1;
}
i=0;
var TMP_series = {
name: '',
data: [],
}
var TIME_SERIES_DATA=[];
var PROC_SERIES_DATA=[];
var time_count=0;
var proc_count=0;
var x = [];
var y = [];
var cat = [];
var out2 = [];
var options_time={
chart: {
renderTo: 'hc_div2',
type: 'scatter',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Highcharts Demo for Graphing',
x: -20 //center
},
subtitle: {
text: 'Graph for '+curr_tier_name,
x: -20
},
yAxis: {
title: {
text: 'Performance Metrics'
},
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
'X: '+this.x +' Y: '+ this.y
}
},
plotOptions: {
scatter: {
marker: {
radius: 2,
}
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: 10,
y: 100,
borderWidth: 0
},
series: TIME_SERIES_DATA
};
var options_proc={
chart: {
renderTo: 'hc_div1',
type: 'scatter',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Highcharts Demo for Graphing',
x: -20 //center
},
subtitle: {
text: 'Graph for '+curr_tier_name,
x: -20
},
yAxis: {
title: {
text: 'Performance Metrics'
},
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
'X: '+this.x +' Y: '+ this.y
}
},
plotOptions: {
scatter: {
marker: {
radius: 2,
}
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: 10,
y: 100,
borderWidth: 0
},
series: PROC_SERIES_DATA
};
var i=0;
if(TIER==tier_max-1){
TIER='OVR';
};
while(i<=CSV_det.length){
csv = CSV_det[i+4];
curr_data=CSV_data[(i/5)];
csv_name = CSV_det[i+1];
csv_tier = CSV_det[i+2];
csv_wl = parseFloat(CSV_det[i+3])+1;
wl_info = '';
if(CSV_det[i+3] !='NA'){
wl_info = ' Workload: '+csv_wl;
};
var j=0;
var line = '';
if(TIER==csv_tier){
TMP_series.data = [];
TMP_series.name = csv_name+wl_info;
while(j<curr_data.length){
XY=curr_data[j].split(',');
X = parseFloat(XY[0]);
Y = parseFloat(XY[1]);
TMP_series.data.push([X,Y]);
j=j+1;
}
j=0;
csv_type=csv.split('/')[3].split('_')[0];
if($.inArray(csv_type,time_ids)==-1){
PROC_SERIES_DATA[proc_count]=[];
PROC_SERIES_DATA[proc_count]=TMP_series;
proc_count=proc_count+1;
}else{
TIME_SERIES_DATA[time_count]=[];
TIME_SERIES_DATA[time_count]=TMP_series;
time_count=time_count+1;
}
}
i=i+5;
};
var chart = new Highcharts.Chart(options_proc);
var chart = new Highcharts.Chart(options_time);
}
A quick explanation on whats going on:
Initially parsing all the data into relevant bins from the arrays string
Creating the two highcharts that wil be displayed
Scanning over the CSVs to find ones that are relevant
For ones that are, reading their Data, and adding it to a TMP_series
Once all data is read, adding the TMP_series to the relevant graph data series
Any help is greatly apprecaited!
Thanks
You need to reset TMP_series to a new object each time you generate a series. Right now you are recycling the same object, and pushing references to the same object into the series arrays. Modify the last bit of your code to read like this:
if(TIER==csv_tier){
TMP_series = {
name : csv_name+wl_info,
data : []
};
while(j<curr_data.length){
XY=curr_data[j].split(',');
X = parseFloat(XY[0]);
Y = parseFloat(XY[1]);
TMP_series.data.push([X,Y]);
j=j+1;
}
j=0;
csv_type=csv.split('/')[3].split('_')[0];
if($.inArray(csv_type,time_ids)==-1){
PROC_SERIES_DATA[proc_count]=[];
PROC_SERIES_DATA[proc_count]=TMP_series;
proc_count=proc_count+1;
}else{
TIME_SERIES_DATA[time_count]=[];
TIME_SERIES_DATA[time_count]=TMP_series;
time_count=time_count+1;
}
}
Notice how at the top of the if, I create a new object with the specified properties, and assign it to the reference TMP_series. Remember, objects are passed by reference, so when you push objects into arrays, you are pushing a reference to the object, not a copy of the object.

Categories

Resources