what should i write in series of highcharts - php

I want to use my database data in series
my table “mob” is something like this :
![my table named "mob"][1]
Icost data in not real
And my code is like this :
<?php
include '../../class/jdf.php';
require_once "../../db.php";
$db = new db();
$query_time = "SELECT DISTINCT iDate FROM mob WHERE 1 ";
$datashow = $db->get_arr($query_time);
$time = array();
foreach ($datashow as $key => $row) {
$format = ' Y/m/d ';
$time[] = jdate($format, $row['iDate']);
}
$query_cost = "SELECT * FROM mob WHERE 1 ";
$data = $db->get_arr($query_cost);
$datamin = $db->get_field('mob','MIN(iCost)','1');
$datamin = $datamin -100;
$datamax = $db->get_field('mob','MAX(iCost)','1');
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script src="../../js/jquery-1.9.1.min.js"></script>
<script src="../../js/highcharts.js"></script>
<style type="text/css">
</style>
<script type="text/javascript">
Highcharts.setOptions({
lang: {
numericSymbols: null
},
});
$(function() {
$('#container').highcharts({
chart:
{
type: 'column'
},
title: {
text: 'my chart '
},
subtitle: {
text: 'mob'
},
xAxis: {
categories: [
<?php
foreach ($time as $value) {
echo "'" . $value . "',";
}
?>
]
},
yAxis: {
min :<?php echo $datamin ?>,
max :<?php echo $datamax ?>,
title: {
text: 'cost'
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: []
});
});
</script>
</head>
<body>
<script src="../../js/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
</body>
</html>
What should I write in series to have a chart like this
![my chart sample is like this][2]
// [1]: http://i.stack.imgur.com/WBJm5.jpg
// [2]: http://i.stack.imgur.com/DYZjm.jpg
Help me please .
Thank you

In your php, prepare correct array (according to avascript structure) and use json_encode(). In javasctrip call $.getJSON(), get data and use in the highcharts.
More information about preprocessing data, here

Related

Date and time wrong on Highstock chart

I have had a look at my chart issue and I think the problem lies in the Highstock code. I have 2 other charts running the same php code and I have only changed from highchart to highstock.
I am trying to add a range selector in my chart. The code for that works in terms of showing the zoom and selector buttons but the date is now showing incorrectly.
I am drawing the data from an online MySQL data base so I its hard to run a demo for you.The timestamp format has worked in my other charts as mentioned.
This first code shows the date correctly
<?php
// 1-test.php
$servername = "localhost";
$dbname = "";
$username = "";
$password = "";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, value1, reading_time FROM Sensor order by reading_time desc limit 40";
$result = $conn->query($sql);
while ($data = $result->fetch_assoc()){
$sensor_data[] = $data;
}
$readings_time = array_column($sensor_data, 'reading_time');
$i = 0;
foreach ($readings_time as $reading){
$readings_time[$i] = date("d-M H:i", strtotime("$reading + 16 hours"));
$i += 1;
}
$value1 = json_encode(array_reverse(array_column($sensor_data, 'value1')), JSON_NUMERIC_CHECK);
$reading_time = json_encode(array_reverse($readings_time), JSON_NUMERIC_CHECK);
/*echo $value1;
echo $reading_time;*/
$result->free();
$conn->close();
?>
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="refresh" content="30">
<link rel="icon" type="image/png" href="favicon.png">
<script src="https://code.highcharts.com/highcharts.js"></script>
<style>
body {
min-width: 310px;
max-width: 1500px;
height: 500px;
margin: 0 auto;
}
h2 {
font-family: Arial;
font-size: 2.5rem;
text-align: center;
}
</style>
<body>
<h2>Test page 2</h2>
<div id="chart-temperature" class="container"></div>
</div>
<script>
var value1 = <?php echo $value1; ?>;
var reading_time = <?php echo $reading_time; ?>;
var chartT = new Highcharts.Chart({
chart: { renderTo : 'chart-temperature',
type: 'spline'
},
title: { text: 'Roof Temperature' },
series: [{
showInLegend: false,
data: value1
}],
plotOptions: {
spline: { animation: false,
dataLabels: { enabled: true }
},
series: { color: '#059e8a' }
},
xAxis: {
type: 'datetime',
categories: reading_time
},
yAxis: {
title: { text: 'Temp (C)' }
},
credits: { enabled: false }
});
</script>
</body>
</html>
Then this code shows the date as Thursday,Jan 1, 00:00:00:001
<?php
$servername = "localhost";
$dbname = "";
$username = "";
$password = "";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, value1, reading_time FROM Sensor order by reading_time desc limit 40";
$result = $conn->query($sql);
while ($data = $result->fetch_assoc()){
$sensor_data[] = $data;
}
$readings_time = array_column($sensor_data, 'reading_time');
$i = 0;
foreach ($readings_time as $reading){
$readings_time[$i] = date("d-M H:i", strtotime("$reading + 16 hours"));
$i += 1;
}
$value1 = json_encode(array_reverse(array_column($sensor_data, 'value1')), JSON_NUMERIC_CHECK);
$reading_time = json_encode(array_reverse($readings_time), JSON_NUMERIC_CHECK);
/*echo $value1;
echo $reading_time;*/
$result->free();
$conn->close();
?>
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="refresh" content="30">
<link rel="icon" type="image/png" href="favicon.png">
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/data.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<style>
body {
min-width: 310px;
max-width: 1500px;
height: 500px;
margin: 0 auto;
}
h2 {
font-family: Arial;
font-size: 2.5rem;
text-align: center;
}
</style>
<body>
<h2>Test Page</h2>
<div id="chart-temperature" class="container"></div>
<script>
var value1 = <?php echo $value1; ?>;
var reading_time = <?php echo $reading_time; ?>;
var chartH = new Highcharts.stockChart({
chart: { renderTo : 'chart-temperature',
type: 'spline'
},
title: { text: 'Roof Temperature' },
series: [{
showInLegend: false,
data: value1
}],
plotOptions: {
spline: { animation: false,
dataLabels: { enabled: true }
},
series: { color: '#059e8a' }
},
rangeSelector: {
buttons: [{
type: 'day',
count: 3,
text: '3d'
}, {
type: 'week',
count: 1,
text: '1w'
}, {
type: 'month',
count: 1,
text: '1m'
}, {
type: 'month',
count: 6,
text: '6m'
}, {
type: 'year',
count: 1,
text: '1y'
}, {
type: 'all',
text: 'All'
}],
selected: 3
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: { second: '%H:%M:%S' },
categories: reading_time
},
yAxis: {
title: { text: 'Temp (C)' }
},
credits: { enabled: false }
});
</script>
</body>
</html>
the first screen shot is working. The second is the wrong date,
Any thoughts on how to change the date
The difference between the charts results from the fact that the second chart is a stock chart, which doesn't support categories on a x-axis. You need to use data in the [x, y] format.
var value1 = [18.10, 14.5];
var reading_time = ['2021-08-22 15:00:53', '2021-08-23 15:00:53'];
var seriesData = value1.map(function(val, index) {
return [new Date(reading_time[index]).getTime(), val];
});
Live demo: http://jsfiddle.net/BlackLabel/xLh7y8d6/
API Reference: https://api.highcharts.com/highcharts/xAxis.type

Data not loading in HighChart from MYSQL

I have recently started working on Highchart. I dont have indepth knowledge. But I am still trying my level best. I have tried few codes, but I didn't get any results. The browser console is not loading anything and it is showing blank. Can you please help me in pointing out what to do next. I tried my level best. Please me out.
Here is my code:
Database Coding: php.data
<?php
//open connection to mysql db
$connection = mysqli_connect("localhost","root","root","demo") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from project_requests";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//close the db connection
mysqli_close($connection);
?>
index.php
<!DOCTYPE HTML>
<?php
include_once 'data.php';
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<style type="text/css">
${demo.css}
</style>
<script type="text/javascript">
$(function () {
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Browser market shares January, 2015 to May, 2015'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
type: 'pie',
name: 'Brands',
colorByPoint: true,
data: [
<?php
//$sql = mysqli_query("select * from project_requests")
while($res=mysql_fetch_array($sql)){
?>
['<?php echo $res['month']; ?>', 45.0],
<?php
}
?>
]
}]
});
});
</script>
</head>
<body>
<script src=
"https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto"></div>
</body>
</html>
MY sql: Database Snapshot
Schema:: Demo Table:: project_requests

Generate HighChart between two dates using Ajax

I am trying to fetch data between two dates using Ajax and displaying the graph using HighCharts.
Below is what i have tried so far;
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="../webroot/css/cake.generic.css" type="text/css" rel="stylesheet">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//default
$('#dynamic_data').change(function() {
var startdate = document.getElementById('startdate').value;
var enddate = document.getElementById('enddate').value;
});
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'Highcharts Chart PHP with MySQL Example',
x: -20 //center
},
subtitle: {
text: 'Sumber : Jabatan XYZ',
x: -20
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Jumlah Pelawat'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>:<b>{point.y}</b> of total<br/>'
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y}'
}
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -40,
y: 100,
floating: true,
borderWidth: 1,
shadow: true
},
series: []
};
function getAjaxData(id) {
$.getJSON("data/data-basic-colm-ajax.php", function(json) {
options.xAxis.categories = json[0]['data']; //xAxis: {categories: []}
options.series[0] = json[1];
chart = new Highcharts.Chart(options);
});
}
});
</script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
</head>
<body>
<a class="link_header" href="/highcharts/"><< Back to index</a>
<div class="menu_top" >
<div id="dynamic_data">
<input type="date" id="startdate">
<input type="date" id="enddate">
</div>
</div>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto;"></div>
</body>
</html>
Here is my data-basic-colm-ajax.php file,
<?php
require '../../conn/connection.php';
$startdate = $_GET['startdate'];
$enddate = $_GET['enddate'];
$result = mysql_query('SELECT DISTINCT(membername), COUNT(membername)
AS member
FROM responses
WHERE timerecorded>=" . $startdate . " AND AND timerecorded<=" . $enddate . " GROUP BY membername;');
$bln = array();
$bln['name'] = 'Bulan';
$rows['name'] = 'Jumlah Pelawat';
while ($r = mysql_fetch_array($result)) {
$bln['data'][] = $r['membername'];
$rows['data'][] = $r['member'];
}
$rslt = array();
array_push($rslt, $bln);
array_push($rslt, $rows);
print json_encode($rslt, JSON_NUMERIC_CHECK);
mysql_close($con);
Since i am new to Ajax so any help will be appreciated.
I'm not sure why you want change event on div, try change into this :
<div id="dynamic_data">
<input type="date" id="startdate">
<input type="date" id="enddate">
// add button
<input type="button" id="myBtn">
</div>
JS
// this function called after button was clicked
$('#myBtn').click(function(){
var startdate = $('#startdate').val(),
enddate = $('#enddate').val();
getAjaxData(startdate, enddate);
});
// i'm assume the queries from database already worked out
// simply use this below code to send parameter during request
function getAjaxData(startdate, enddate) {
$.getJSON( "data/data-basic-colm-ajax.php", { startdate: startdate, enddate: enddate }, function(json) {
options.xAxis.categories = json[0]['data']; //xAxis: {categories: []}
options.series[0] = json[1];
chart = new Highcharts.Chart(options);
});
}
If you wanna display the chart at first load page, then call getAjaxData(startdate, enddate) with default value for date.

Highcharts gauge, set retrieved data after $.getJSON call

I am having difficulties to get the data received from PHP script and set it into the Gauge graph.
I am getting the json result correctly, just do not know how to set it to the right Highchart gauge variables (gaugeOptions).
I'd like to put in #container-C_2 the returned values from PHP, so configure the min, max and set the value on the gauge graph.
strong text
I think In the $.getJSON() body I need to call
$('#container-C_2').highcharts( with some arguments, but don't know how..
Can someone help me here?
Many thanks.
PHP
$result = array();
$result['name'][0] = 'A';
//--some values
$result['min'][] = 10;
$result['max'][] = 50;
$result['val'][] = 20;
$json = array();
array_push($json,$result);
print json_encode($json);
Client side:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<style type="text/css">
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var gaugeOptions = {
chart: {
type: 'solidgauge'
},
title: null,
pane: {
center: ['50%', '100%'],
size: '100%',
startAngle: -90,
endAngle: 90,
background: {
backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || '#EEE',
innerRadius: '60%',
outerRadius: '100%',
shape: 'arc'
}
},
tooltip: {
enabled: false
},
// the value axis
yAxis: {
stops: [
[0.25, '#DF5353'], // red
[0.5, '#DDDF0D'], // yellow
[0.75, '#55BF3B'], // green
],
lineWidth: 0,
minorTickInterval: null,
tickPixelInterval: 400,
tickWidth: 0,
title: {
y: -70
},
labels: {
y: 16
}
},
plotOptions: {
solidgauge: {
dataLabels: {
y: 5,
borderWidth: 0,
useHTML: true
}
}
}
}; //-- gaugeOptions
// The C_1 gauge
$('#container-C_1').highcharts(Highcharts.merge(gaugeOptions, {
yAxis: {
min: -50,
max: 50,
title: {
text: 'graph 1'
}
},
credits: {
enabled: false
},
series: [{
name: 'C_1',
data: [-50],
dataLabels: {
format: '<div style="text-align:center"><span style="font-size:25px;color:' +
((Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black') + '">{y}</span><br/>' +
'<span style="font-size:12px;color:silver"> graph... </span></div>'
},
tooltip: {
valueSuffix: ' graph... '
}
}]
}));
// The C_2 gauge
$('#container-C_2').highcharts(Highcharts.merge(gaugeOptions, {
yAxis: {
min: -50,
max: 50,
title: {
text: 'C_2'
}
},
series: [
{
name: 'C_2',
data: [45],
dataLabels: {
format: '<div style="text-align:center"><span style="font-size:25px;color:' +
((Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black') + '">{y:.1f}</span><br/>' +
'<span style="font-size:12px;color:silver"> graph... </span></div>'
},
tooltip: {
valueSuffix: ' graph... '
}
}
]
})); //--container-C_2
$.getJSON("query.php", function(json) {
//this WORKS!
alert("name, grow_rate: " + json[0]['name'] + ","+ json[0]['val'] );
//This seems not to have any effect
gaugeOptions.yAxis.min = json[0]['min'];
gaugeOptions.yAxis.max = json[0]['max'];
gaugeOptions.yAxis.title.text = 'JUST SOME TEXT...';
gaugeOptions.series[0] = {};
//gaugeOptions.series[0].name = json[0]['name'][0];
gaugeOptions.series[0].name = json[0]['name'];
gaugeOptions.series[0].data = json[0]['val'];
//-- stucked here, how can I passed retreived values to the graph?
// chart = new Highcharts.merge(gaugeOptions);
});
}); //-- ready()
</script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script src="http://code.highcharts.com/highcharts-more.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/highcharts-more.js"></script>
<script src="http://code.highcharts.com/modules/solid-gauge.src.js"></script>
<div style="width: 600px; height: 400px; margin: 0 auto">
<div id="container-C_1" style="width: 300px; height: 200px; float: left"></div>
<div id="container-C_2" style="width: 300px; height: 200px; float: left"></div>
</div>
</head>
<body>
</body>
</html>
var point = $('#container-C_2').highcharts().series[0].points[0];
point.update(json[0]['val']);
Instead of this
//This seems not to have any effect
gaugeOptions.yAxis.min = json[0]['min'];
gaugeOptions.yAxis.max = json[0]['max'];
gaugeOptions.yAxis.title.text = 'JUST SOME TEXT...';
gaugeOptions.series[0] = {};
//gaugeOptions.series[0].name = json[0]['name'][0];
gaugeOptions.series[0].name = json[0]['name'];
gaugeOptions.series[0].data = json[0]['val'];

Creating Pie chart in High Chart

I'm having a table in MySQL with the following data
Buy_client Amount
ABC 6597
XYZ 4479
PQR 2075
qqq 1706
ttt 1030
Other 450
I want to show the following data in a Pie Chart in High Charts. Someone please help me with this. I'm new to both PHP and HighCharts
Question 1: I need to Create a Pie chart from this data
Question 2: I'm using HighCharts for this. Someone please help me to do this in HighCharts
I have used the following code to do this but it doesn't show the info in a pie chart but just display the data in the web browser
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<?php
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("offlinesurv", $con);
$my_data = mysql_query("SELECT * FROM top_buy_clients");
while($row = mysql_fetch_array($my_data)) {
echo $row['buy_client'] . "\t" . $row['qty']. "\n";
}
?>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(function () {
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Browser market shares at a specific website, 2010'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage}%</b>',
percentageDecimals: 1
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: 'green',
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';
}
}
}
},
series: [{
type: 'pie',
name: 'Browser share',
data: [ <?php echo $row; ?>]
}]
});
});
});
</script>
</head>
<body>
<script src="js/highcharts.js"></script>
<script src="js/exporting.js"></script>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
In your php...where you make the query to the database....in the while loop, you need to construct and string and in the end of the loop the string should looks like:
$my_data = "['ABC', 6597],
['XYZ', 4479],
['PQR', 2075],
['qqq', 1706],
['ttt', 1030],
['Others', 450] ";
Then in your javascript file, you should have a line like this
series: [{
type: 'pie',
name: 'Pie Data',
data: [
<?php echo $my_data; ?>
]
}]
It's very simple.
Saludos.

Categories