How to change json encode to array string - javascript

I have a task to solve how to change JSON encode to array string,
look at my code below: I have
["11:00"]["09:00"]["01:00"]["12:00"]["11:00"]["10:00"]["01:00"]["00:00"]["23:00"]["22:00"]
how to change it to become
["11:00","09:00","01:00","11:00","10:00","01:00","00:00","23:00","22:00"]
My stats.php looks like this:
out .= ' <div class="col-lg-5 col-md-5 col-sm-5 col-lg-offset-1 col-md-offset-1 col-sm-offset-1" style="height: 300px">';
$out .= ' <div class="chartjs-size-monitor">';
$out .= ' <div class="chartjs-size-monitor-expand">';
$out .= ' <div class=""></div>';
$out .= ' </div>';
$out .= ' <div class="chartjs-size-monitor-shrink">';
$out .= ' <div class=""></div>';
$out .= ' </div>';
$out .= ' </div>';
$out .= ' <canvas id="myChart2" class="canpas chartjs-render-monitor" style="display: block; width: 454px; height: 300px;" width="454" height="300"></canvas>';
$out .= ' </div>';
$graph_query = mssql_query("SELECT TOP 100 Convert(nvarchar,dtDate,108) AS Date, serial, nAverageUser, nMaxUser FROM tbl_ServerUser_Log ORDER BY serial DESC");
$i = 1;
while ($graph = mssql_fetch_array($graph_query)) {
$graph['nMaxUser'] = round($graph['nMaxUser'] * $percent_inc);
$graph['nAverageUser'] = round($graph['nAverageUser'] * $percent_inc);
$serie1->addPoint(new Point($graph['Date'], $graph['nMaxUser']));
$serie2->addPoint(new Point($graph['Date'], $graph['nAverageUser']));
$date = date('H:i', strtotime($graph['Date']));
$convert = json_encode(str_split($date, 5));
// $convert = str_replace('][','',$convert);
echo $convert;
}
I want to show a chart and send the value in HTML.
The HTML shall look like this:
<script type="text/javascript">
var ctx = document.getElementById('myChart2').getContext('2d');
var myChart2 = new Chart(ctx, {
type: 'line',
data: {
labels: ['00:00','01:00','02:00','03:00','04:00','05:00','06:00','07:00','08:00','09:00','10:00','11:00','12:00','13:00','14:00','15:00','16:00','17:00','18:00','19:00','20:00','21:00','22:00','23:00'], //Jamnya
datasets: [{
backgroundColor: 'rgba(232,72,163,0.2)',
borderColor: '#e848a3',
label: '29 May 2020',
data: [807,657,600,578,565,576,611,855,625,573,571,584,607,647,771,943,920,647,622,608,722,832,902,1062],
fill: true,
pointRadius: 5,
pointHoverRadius: 10,
showLine: true
}]
}, options: {
responsive: true,
maintainAspectRatio: false,
title: {
display: true,
text: 'Total Online Yesterday',
position: 'top',
fontSize: 15,
fontStyle: 'bold'
},
legend: {
display: false
},
elements: {
point: {
pointStyle: 'circle'
}
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'TIME'
},
ticks: {
major: {
fontStyle: 'bold',
fontColor: '#FF0000'
}
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'TOTAL ONLINE'
}
}]
},
tooltips:{
callbacks: {
title: function(tooltipItem, data) {
return '29 May 2020 '+data['labels'][tooltipItem[0]['index']];
},
label: function(tooltipItem, data) {
return 'TOTAL : '+data['datasets'][0]['data'][tooltipItem['index']]+'';
},
},
titleFontSize: 15,
bodyFontSize: 15,
displayColors: false
}
}
});
</script>
I just want to show my chart from manual value to query value that I catch from an SQL server.
Thanks in advance for answering my question.

Don't echo JSON every time through the loop. Put the times in a single array, and echo the JSON at the end.
$dates = [];
while ($graph = mssql_fetch_array($graph_query)) {
$graph['nMaxUser'] = round($graph['nMaxUser'] * $percent_inc);
$graph['nAverageUser'] = round($graph['nAverageUser'] * $percent_inc);
$serie1->addPoint(new Point($graph['Date'], $graph['nMaxUser']));
$serie2->addPoint(new Point($graph['Date'], $graph['nAverageUser']));
$date = date('H:i', strtotime($graph['Date']));
$dates[] = $date;
echo $convert;
}
echo json_encode($dates);

Related

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.

Highchart pie-basic

Good day guys. So I've got some kind of problem of my highcharts pie, where I've got only two items/legends where 1995 and 1996. I've got a data in 1995 where there are 2 and 1996 is 0.
It displays the pie chart, but the problem is that it's wrong in percentage. As you can see in the image below it show both the 1995 and 1996.
The 1995 should be in 100% and not in 10% because i've got only two items, the 1996 is correct however because i've got no data.
Here is my php code
<?php
require '/db/database_configuration.php';
$_1995 = mysqli_query($conn, "SELECT COUNT(*) AS Total FROM `tblalumni` WHERE yeargrad LIKE '1995' and alum_status LIKE 2");
$_1996 = mysqli_query($conn, "SELECT COUNT(*) AS Total FROM `tblalumni` WHERE yeargrad LIKE '1996' and alum_status LIKE 2");
$_1995 = mysqli_fetch_array($_1995);
$_1996 = mysqli_fetch_array($_1996);
// displays zero if none
if (empty($_1995['Total'])) { $_1995 = '0'; } else { $_1995 = $_1995['Total'];}
if (empty($_1996['Total'])) { $_1996 = '0'; } else { $_1996 = $_1996['Total'];}
$ans_1995 = '1995';
$ans_1996 = '1996';
$Data95 = $_1995;
$Data96 = $_1996;
?>
Here is my javascript
<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: [{
name: 'Brands',
colorByPoint: true,
data: [{
name: <?php echo json_encode($ans_1995); ?>,
y: [<?php echo $Data95; ?>]
}, {
name: <?php echo json_encode($ans_1996); ?>,
y: [<?php echo $Data96; ?>]
}]
}]
});
});
</script>
Can anyone help me?
change
series: [{
name: 'Brands',
colorByPoint: true,
data: [{
name: <?php echo json_encode($ans_1995); ?>,
y: [<?php echo $Data95; ?>]
}, {
name: <?php echo json_encode($ans_1996); ?>,
y: [<?php echo $Data96; ?>]
}]
}]
to
series: [{
name: 'Brands',
colorByPoint: true,
data: [{
name: <?php echo json_encode($ans_1995); ?>,
y: <?php echo $Data95; ?>
}, {
name: <?php echo json_encode($ans_1996); ?>,
y: <?php echo $Data96; ?>
}]
}]
Just remove brackets.. HAHAHAH

Line graph data HighChart JS cannot shown

i wannna make a line graph using highchart JS with data from my SQL, but unfortunately the graph just shown like this :
the graph just shown a Xline and Yline but not a data
and this is my sql code
$sqlX=mysql_query("SELECT DISTINCT DAY(tgl_daftar) as value FROM pasien WHERE MONTH(tgl_daftar) = '06' AND YEAR(tgl_daftar)='2016'")or die(mysql_error()) ;
and this my php and JS code :
<script src="js/jquery.min.js"></script>
<script src="js/highcharts.js"></script>
<script src="js/exporting.js"></script>
<script type="text/javascript">
var chart1 ;
$(document).ready(function() {
chart1 = new Highcharts.Chart({
chart: {
renderTo: 'grafik',
type: 'column'
},
title: {
text: 'Data Pendaftaran Pasien Baru Per Bulan',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: [<?php while($r=mysql_fetch_array($sqlX)){ echo "'".$r['value']."',";} ?>]
},
yAxis: {
title: {
text: 'Jumlah'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
valueSuffix: ''
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: [{
name: <?php echo "'".$namabulan."'" ; ?>
<?php
while($date=mysql_fetch_array($sqlX)){
$date=$date['value'];
$sql_jumlah = "SELECT tgl_daftar, COUNT(*) as jumlah_pasien
FROM pasien
WHERE
DAY(tgl_daftar) = '$date'
AND MONTH(tgl_daftar)='$bulan' AND YEAR(tgl_daftar) = '$namatahun'";
$query_jumlah = mysql_query( $sql_jumlah ) or die(mysql_error());
while( $data = mysql_fetch_array( $query_jumlah ) ){
$jumlah = $data['jumlah_pasien']; }
?>
data: [<?php echo $jumlah ; ?>]
<?php
} ?>
}]
});
});
</script>
thanks, Any help would be really appreciated

HIghcharts onclick change xAxis plotline according to some value

I have to shift my xAxis plotline according to Some specific time which could be described outside of the Graph using Onclick Event. Here my Code is
HTML Code
<li class="selected" onclick="exp_chng(this.id)" id="time1"><?php
date_default_timezone_set("Asia/Kolkata");
echo date('H:i'); ?></li>
<li onclick="exp_chng(this.id)" id="time2"><?php $currentDate = strtotime(date('H:i')); $futureDate = $currentDate+(60*1); echo $formatDate = date("H:i", $futureDate); ?> </li>
<li onclick="exp_chng(this.id)" id="time3"><?php $currentDate = strtotime(date('H:i')); $futureDate = $currentDate+(60*2); echo $formatDate = date("H:i", $futureDate); ?></li>
<li onclick="exp_chng(this.id)" id="time4"><?php $currentDate = strtotime(date('H:i')); $futureDate = $currentDate+(60*3); echo $formatDate = date("H:i", $futureDate); ?></li>
And the Highcharts initialization is
xAxis: {
type: 'datetime',
type: 'datetime',
minTickInterval: 1000 * 60, //one minute
gridLineWidth: 0.1,
plotLines: [{
value: exp_time, // Value of where the line will appear
width: 2 ,
color: '#A28F29',
// dashStyle: 'dash',
id: 'plotline1',
label: {
text: 'Expiration time',
style: {
color: '#686A3B',
//#A28F29
fontWeight: 'bold'
}
}
}]
},
Javascript code
function exp_chng(id)
{
var time = $('#'+id).html();
var chart = $("#tv_chart_container").highcharts();
chart.xAxis[0].removePlotLine('plotline1');
var check_1 =chart.xAxis[0].addPlotLine({
value: time,
color: '#A28F29',
width: 2,
id: 'plotline1',
label: {
text: 'Expiration time',
style: {
color: '#686A3B',
fontWeight: 'bold'
}
}
});
console.log(check_1);
}

Highstock don't draw

http://www.highcharts.com/stock/demo/basic-line
It's my code for json.php
<?php
header("content-type: application/json");
define('HOST', 'localhost');
define('USER', 'root');
define('PASSWORD', 'password');
define('NAME_BD', 'bd');
$connect = mysql_connect(HOST, USER, PASSWORD)
or die("die"
.mysql_error( ));
mysql_select_db(NAME_BD, $connect)
or die ("wtf"
.mysql_error( ));
$result = mysql_query("SELECT UNIX_TIMESTAMP(`Time`) * 1000 as datetime, `Current A` as A FROM `Table`")
or die ("die".mysql_error( ));
while ($row = mysql_fetch_array($result)) {
$data[] = $row['datetime'];
$datab[] = $row['A'];
}
echo '?(' . "\n" . '['. "\n";
$count = count($data);
for ($i=0; $i<$count; $i++)
{
echo '['. str_replace('"', "", json_encode($data[$i], JSON_HEX_APOS)) . ',' . str_replace('"', "", json_encode($datab[$i], JSON_HEX_APOS)) .']' . ',' . "\n";
}
echo ']);';
?>
I refresh my page and highstock don't draw. Please help me.
It's my stock.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highstock 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 () {
$.getJSON('http://192.168.1.175/json.php', function (data) {
// Create the chart
$('#container').highcharts('StockChart', {
rangeSelector : {
selected : 1
},
title : {
text : 'AAPL Stock Price'
},
series : [{
name : 'AAPL',
data : data
}]
});
});
});
</script>
</head>
<body>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<div id="container" style="height: 400px; min-width: 310px"></div>
</body>
</html>
Stock.html call json.php but when a refresh stock.html i don't see draw.
Please help me
Please try below code
in Ajax code
function drawGrap()
{
$.ajax({
type: "POST",
url: 'graph.php',
data: '',
success: function(json) {
drawSalesChart(json);
}
});
}
in graph.php
<?php
if(!empty($data))
{
foreach ($data as $d)
{
$time = strtotime($d['date']);
$date = date("Y-m-d",$time);
$graphData[$date][0] = 'Date.UTC('. date("Y",$time) .','. (date("m",$time)-1) .','. date("d",$time) .')';
$graphData[$date][1] = $d['count'];
}
}
sort($graphData);
//Convert result array to json format
$jsonGraphData = json_encode($graphData);
$jsonGraphData = str_replace('"', '', $jsonGraphData);
echo $jsonGraphData;
?>
After response
function drawSalesChart( data)
{
$('#GraphID').css("height", "400px");
$('#GraphID').highcharts('StockChart', {
title: {
text: 'Daily Sales'
},
colors: ['#920000'],
navigator: {
enabled: false
},
rangeSelector: {
selected: 5,
buttons: [
{
type: 'week',
count: 1,
text: '1 Week'
},
{
type: 'month',
count: 1,
text: '1 Month'
},
{
type: 'month',
count: 3,
text: '3 Months'
},
{
type: 'month',
count: 6,
text: '6 Months'
},
{
type: 'year',
count: 1,
text: '1 Year'
},
{
type: 'all',
text: 'All'
}
],
buttonTheme: {
width: 100,
padding: 5,
style: {
color: '#000000'
}
}
},
series: [{
name: 'Kr',
type: 'area',
data: eval(data),
tooltip: {
valueDecimals: 2
},
fillColor: {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops: [
[0, '#FF4848'],
[1, '#ffe1e1'],
]
}
}]
});
}

Categories

Resources