Unable to get HighCharts to run properly pulling from JSON - javascript

I'll start by saying I'm completely new to Javascript. I have worked with Java and PHP more than anything.
I copied much of the code from the example and have tried tinkering with it to get it to run but have not had any luck. The original example in JSFiddle is here: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/stock/demo/compare/
Any input is appreciated.
<?php
echo <<< 'EOT'
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://code.highcharts.com/highstock.js"></script>
<script src="https://code.highcharts.com/exporting.js"></script>
</head>
<body>
EOT;
require_once('hvst.php'); // Generates the JSON file using json_encode();
echo <<< 'EOT'
function createChart() {
var fields = ['humidity', 'curtemp'];
Highcharts.stockChart('container', {
rangeSelector: {
selected: 4
},
yAxis: {
labels: {
formatter: function () {
return (this.value > 0 ? ' + ' : '') + this.value + '%';
}
},
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2,
split: true
},
series: seriesOptions
});
$.each(fields, function (timestamp, curtemp) {
$.getJSON('chart1.json', function (humidity) {
seriesOptions[timestamp] = {
name: curtemp,
data: humidity
},
seriesCounter += 1;
if (seriesCounter === fields.length) {
createChart();
}
});
});
};
</script>
<div id="container" style="height: 400px; min-width: 400px"></div>
</body>
</html>
EOT;
?>
Edit: hvst.php
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
//Set JSON header
header("Content-type: text/json");
include 'dbread.php';
//include 'correlate.php';
// Get last 5 days
$days=5;
$resultSet1 = readDB('SELECT timestamp,humidity,curtemp FROM public."WeatherData" WHERE timestamp > NOW()-INTERVAL \''.$days.' days\';');
$fp = fopen('chart1.json', 'w');
fwrite($fp, json_encode($resultSet1,JSON_PRETTY_PRINT|JSON_NUMERIC_CHECK));
fclose($fp);
?>
Here's a sample of the first few lines from the JSON output:
[
{
"timestamp": "2016-11-05 10:10:02.427425",
"humidity": 48,
"curtemp": 46
},
{
"timestamp": "2016-11-05 10:10:03.83401",
"humidity": 48,
"curtemp": 46
},

Related

Highcharts loaded via ajax, issue to dynamically create yAxis

I have a page that dynamically updates a HighCharts graph from a multiselect dropdown.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/series-label.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
</head>
<body>
<!-- FIELDS -->
<div id="fields">
<form method="post" action="">
<select id="f" name="f[]" multiple>
<option value="rss1" select>1RSS(dB)</option>
<option value="rss2">2RSS(dB)</option>
<option value="rqly">RQly(%)</option>
<option value="rsnr">RSNR(dB)</option>
</select>
</form>
</div>
<!-- GRAPH -->
<div id="graph">No selection</div>
<script>
var updateChart = function(json) {
// console.log(json)
var options = {
chart: {
renderTo: 'graph',
type: 'line',
zoomType: 'x'
},
title: { text: null },
plotOptions: {
series: {
label: {
connectorAllowed: false
},
pointStart: 0
}
},
series: []
}
options.series = json;
var chart = new Highcharts.Chart(options);
// update yaxis
for (i=0; i<json.length; i++) {
if(i==0) {
// it seems that a yAxis already exist when graph is initialized. Did not find a smarter way to destroy it...
chart.yAxis[0].update({ title: { text: json[i].name }});
} else {
chart.addAxis({ title: { text: json[i].name } });
}
}
}
$(document).ready(function() {
$('#f').change(function() {
var requestParams = { f: $('#f').val() };
$.post('analysisajax.php', requestParams, updateChart);
});
});
</script>
</body>
</html>
Now, my analysisajax.php file looks like this:
<?php
header("Content-type: text/json");
// Initialize the session
session_start();
// Include config file
require_once "config.php";
$jsonObject = array();
$yaxis = 0;
foreach($_POST["f"] as $v) {
$data = array();
$sql = "SELECT $v FROM log WHERE id_user = " . $_SESSION["id_user"];
$result = $link->query($sql);
while($row = $result->fetch_row()) {
$data[] = $row[0];
}
$jsonObject[] = array(
"name" => $v,
"data" => $data,
"yAxis"=>$yaxis
);
$yaxis++;
}
$myJSON = json_encode($jsonObject, JSON_NUMERIC_CHECK);
echo $myJSON;
// Close connection
mysqli_close($link);
?>
When I'm selecting 1 value from the form, the graph loads without problem, but as soon as more than 1 value is selected from the dropdown, the graph fails with the following trace:
highcharts.src.js:498 Uncaught Error: Highcharts error #18: www.highcharts.com/errors/18
at Object.a.error (highcharts.src.js:498)
at highcharts.src.js:32669
at Array.forEach (<anonymous>)
at r.<anonymous> (highcharts.src.js:32621)
at a.fireEvent (highcharts.src.js:2635)
at r.bindAxes (highcharts.src.js:32618)
at r.init (highcharts.src.js:32482)
at a.Chart.initSeries (highcharts.src.js:26913)
at highcharts.src.js:28765
at Array.forEach (<anonymous>)
I feel that the issue is coming from my dynamic construction of yAxis but can't find a way to make it work. Any idea? Thanks a lot.
I eventually made it work with the following solution:
In the analysisajax.php script, I no longer generate the yaxis. I only send name and data.
The code to generate the graph now looks like this:
var updateChart = function(json) {
//console.log(json)
var options = {
chart: {
renderTo: 'graph',
type: 'line',
zoomType: 'x'
},
title: { text: null },
yAxis:[],
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'bottom'
},
plotOptions: {
series: {
label: {
connectorAllowed: false
},
pointStart: 0
}
},
series: [],
tooltip: { shared: true }
}
var chart = new Highcharts.Chart(options);
// update axis and series
for (i=0; i<json.length; i++) {
// add axis
chart.addAxis({ title: { text: json[i].name } });
// add serie
var a = chart.series.length;
var seriesOptions = {
name: json[i].name,
data: json[i].data,
yAxis: a
}
chart.addSeries(seriesOptions,true);
chart.options.series.push(seriesOptions);
}
}
$(document).ready(function() {
$('#f').change(function() {
var requestParams = { f: $('#f').val() };
$.post('analysisajax.php', requestParams, updateChart);
//return false;
});
});

how to draw high chart using function?

$(document).ready(function() {
Highcharts.setOptions(Highcharts.theme);
$('#div-chart').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Average Purchase',
align: 'center'
},
subtitle: {
text: ' '
},
xAxis: {
categories: <?php echo json_encode($result['day']) ?>,
crosshair: true
},
yAxis: {
min: 0,
title: {
text: 'Amount (Millions)'
}
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Purchase',
data: <?php echo json_encode($result['amount']) ?>
}]
});
});
In $(document).ready(function(){}); I'm defining the properties how my chart is drawn, what comes to x-axis and y-axis and properties of it. But, now I want to build a function in which I pass argument whether I want to draw high chart or canvas and then that function draw chart. How to start this? Can anyone help?
<?php
//dummy data
$result['day'] = array('Sun', 'Man', 'Tue', 'Wed');
$result['amount'] = array(1, 32, 324, 3531, 15, 6);
$result['chartType'] = 'canvas';
//$result['chartType'] = 'normal'; //this one to draw normal chart
?>canvas
<script
src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
<script type="text/javascript" src="http://code.highcharts.com/4.0.4/highcharts.js"></script>
<script type="text/javascript" src="http://code.highcharts.com/4.0.4/modules/exporting.js"></script>
<style type="text/css">
#div-chart {
max-width: 800px;
height: 400px;
margin: 1em auto;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
DrawhighChart(); //first draw high chart by default and make it hidden by
<?php if($result['chartType'] === 'canvas'){
?> DrawCanvas($('#div-chart').highcharts());
<?php } else { ?> $('#div-chart').show(); <?php } ?>
});
function DrawCanvas(chart) {
EXPORT_WIDTH = 1000;
var render_width = EXPORT_WIDTH;
var render_height = render_width * chart.chartHeight / chart.chartWidth
// Get the cart's SVG code
var svg = chart.getSVG({
exporting: {
sourceWidth: chart.chartWidth,
sourceHeight: chart.chartHeight
}
});
// Create a canvas
var canvas = document.createElement('canvas');
canvas.height = render_height;
canvas.width = render_width;
document.body.appendChild(canvas);
// Create an image and draw the SVG onto the canvas
var image = new Image;
image.onload = function() {
canvas.getContext('2d').drawImage(this, 0, 0, render_width, render_height);
};
image.src = 'data:image/svg+xml;base64,' + window.btoa(svg);
}
function DrawhighChart(){
Highcharts.setOptions(Highcharts.theme);
$('#div-chart').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Average Purchase',
align: 'center'
},
subtitle: {
text: ' '
},
xAxis: {
categories: <?php echo json_encode($result['day']) ?>,
crosshair: true
},
yAxis: {
min: 0,
title: {
text: 'Amount (Millions)'
}
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Purchase',
data: <?php echo json_encode($result['amount']) ?>
}]
});
}
</script>
<div id='div-chart' style="display: none"></div>
Note:
If you want to change the properties dynamically follow the same thing you did for x-axis values for example if you want to change the title then
title: {
text: '<?php echo $result["title"] ?>',
align: 'center'
},
Look at the official documentation. You have to call Highcharts.chart('div-chart', { ... your settings ... }. You can assign this to a variable, but not to your div like you did above. And what do you mean with draw canvas OR Highchart?
I think what Thamaraiselvam ment was:
$(document).ready(function() {
drawChart(chart_type, args...);
});
function drawChart(chart_type, args....){
if (type === 'highchart') {
drawHighChart(args);
} else if (type === 'canvas'){
drawCanvas(args);
}
}
function drawHighChart(args){
}
function drawCanvas(args){
}
Not directly related but still. I suggest you to look on the side of Jquery which gives the possibility to produce a lot of fancy graphic output with usually less effort than with javascript. see this documentation. Greetings andy

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.

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'],
]
}
}]
});
}

Post request inside php code var anidade

I am working with Dygraphs to chart Arduino sensor data.I need to get a subtract between two data so i am using php inside a script function but it doesn't work.It is possible to include
<script type="text/javascript">
var csv = [
'<?php
$row = 1;
if (($handle = fopen("https://api.thingspeak.com/channels/***/feed.csv?key=***&start=<?php echo $_POST['day_ini'];?>%20<?php echo $_POST['hour_ini'];?>&end=<?php echo $_POST['day_end'];?>%20<?php echo $_POST['hour_end'];?>", "r")) !== FALSE) {
...
?>','2015-11-02 20:54:50 UTC,1049703,5,5'
];
This is all my function code:
<script type="text/javascript">
var csv = [
'<?php
$row = 1;
if (($handle = fopen("https://api.thingspeak.com/channels/***/feed.csv?key=***&start=2015-11-02%2020:50:45&end=2015-11-02%2021:50:45", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 50, ",")) !== FALSE) {
if($row == 1){ $row++; continue; }
$num = count($data);
for ($c=0; $c < $num; $c++) {
if(strpos($data[$c], 'Finished') !== false) {
$c++;
echo $data[$c] . "," ; }
Else{
echo $data[$c] . "," ;
}
}
}
fclose($handle);
}
?>','2015-11-02 20:54:50 UTC,1049703,5,5'
//... etcetera
];
function getPairDifference(pair) {
//"pair" is a zero-based integer.
// "0" will return a difference between csv rows "0" & "1"
// "1" will return a difference between csv rows "1" & "2"
// etcetera...
var firstVal = parseInt(csv[pair].split(",")[3]);
var secondVal = parseInt(csv[pair + 1].split(",")[3]);
return firstVal - secondVal;
}
for (var i = 0; i < csv.length; i += 1) {
// Demo code to visualize numbers.
// Actual function call of interest is simply "getPairDifference( i )"
var plot = getPairDifference(i);
// $("<div></div>").text(plot).appendTo("body");
$(function() {
$("#chart3").chart({
template: "line_basic_6",
tooltips: {
serie1: [plot],
width:20,
height:15,
},
values: {
serie1: [plot]
},
labels: ["Period 1","Period 2"],
defaultSeries: {
type: "bar",
stacked: true
},
series: {
serie3: {
type: "line",
stacked: false,
axis: "r"
}
},
axis: {
r: {
max: 100,
suffix: "%"
}
}
});
});
$.elycharts.templates['line_basic_6'] = {
type: "line",
margins: [10, 40, 40, 30],
defaultSeries: {
highlight: {
newProps: {
r: 8,
opacity: 1
},
overlayProps: {
fill: "white",
opacity: 0.2
}
}
},
series: {
serie1: {
color: "90-#003000-#009000",
tooltip: {
frameProps: {
stroke: "green"
}
}
},
},
defaultAxis: {
labels: true
},
axis: {
x: {
labelsRotate: 0,
labelsProps: {
font: "11px Verdana"
}
}
},
features: {
grid: {
draw: true,
forceBorder: true,
ny: 5
}
},
barMargins: 180
};
}
</script>
Thanks in advance.
no need to echo like that and you are using <?php inside another <?php before closing that.
<script type="text/javascript">
var csv = [
'<?php
$row = 1;
if (($handle = fopen("https://api.thingspeak.com/channels/***/feed.csv?key=***&start={$_POST['day_ini']}%20{$_POST['hour_ini']}&end={$_POST['day_end']}%20{$_POST['hour_end']}", "r")) !== FALSE) {
}
?>', '2015-11-02 20:54:50 UTC,1049703,5,5'
];
</script>
And i am not sure of }, please check that once.
You have missunderstood something about PHP and Javascript.
Javascript gets sended to the Client, so it works in the Browser and also get's executed.
PHP altough gets executed on the Server first, there lies your problem, you can't execute on the Client something that needs to be done by a Server.

Categories

Resources