Trouble getting value from php and display on html [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have two files. One is tempTesting.php and another is using flot to graph the data displayed on project.html. But I cannot get the value from the tempTesting.php and display it on project.html.
When I run the project.html it gives me a syntax error on this line:
var dat = <?php echo $return; ?>;
tempTesting.php
<?php
$return="[123456789,22.55],[234567891,22.32]";
$maxtemp=-10;
$mintemp=50;
?>
project.html
<!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>Flot For Temperature Project</title>
<script src="jquery.js" language="javascript" type="text/javascript"></script>
<script src="jquery.flot.js" language="javascript" type="text/javascript"></script>
<!--[if IE]><script language="javascript" type="text/javascript" src="excanvas.pack.js"></script><![endif]-->
<script type="text/javascript" src="jquery.flot.time.js"></script>
<script type="text/javascript" src="jquery.flot.symbol.js"></script>
<script type="text/javascript" src="jquery.colorhelpers.js"></script>
<script type="text/javascript" src="jquery.flot.canvas.js"></script>
<script type="text/javascript" src="jquery.flot.categories.js"></script>
<script type="text/javascript" src="jquery.flot.crosshair.js"></script>
<script type="text/javascript" src="jquery.fillbetween.js"></script>
<script type="text/javascript" src="jquery.flot.image.js"></script>
<script type="text/javascript" src="jquery.flot.navigate.js"></script>
<script language="javascript" type="text/javascript">
$(function () {
var dat = <?php echo $return;?>;
var options = {
xaxis: { mode: "time", timeformat: "%h:%M %d.%m.%y", labelWidth: "10" },
series: {
lines: { show: true, fill: true, fillColor: "rgba(0,0,0,0.2)" },
points: { show: true, fill: false },
shadowSize: 5,
color: "rgba(0,0,0,0.8)"
},
grid: { hoverable: true, clickable: true },
yaxis: { min: <?php echo $mintemp-2;?> , max: <?php echo $maxtemp+2;?>, tickFormatter: function (v, axis) { return v.toFixed(axis.tickDecimals) +"°C" }},
selection: { mode: "x", color: "rgba(125,0,0,0.6)" },
legend: { show: true, position: "se", backgroundOpacity: 0.4, backgroundColor: "rgb(255,255,255)", labelBoxBorderColor: "rgb(0,0,0)"},
};
var plot = $.plot($("#placeholder"),[ { data: dat, label: "Study Temp", color:"#333"} ], options);
var overview = $.plot($("#overview"), [ { data: dat, label: "Min: °C, Max: °C", color: "#333"} ], {
series: {
color: "rgba(0,0,0,0.8)",
lines: { show: true, lineWidth: 1, fill: true, fillColor: "rgba(0,0,0,0.2)" },
shadowSize: 0
},
xaxis: { ticks: [], mode: "time" },
yaxis: { ticks: [], min: 0, autoscaleMargin: 0.1 },
selection: { mode: "x", color: "rgba(125,0,0,0.6)" },
legend: { show: true, position: "se", backgroundOpacity: 1, backgroundColor: "rgb(255,255,255)", labelBoxBorderColor: "rgb(0,0,0)" }});
$("#placeholder").bind("plotselected", function (event, ranges) {
plot = $.plot($("#placeholder"), [dat],
$.extend(true, {}, options, {
xaxis: { min: ranges.xaxis.from, max: ranges.xaxis.to }
}));
overview.setSelection(ranges, true);
});
$("#overview").bind("plotselected", function (event, ranges) {
plot.setSelection(ranges);
});
var humanTime;
var jstime;
function showTimes(t) {
var datum = new Date(parseFloat(t));
humanTime = datum.toUTCString();
}
function showTooltip(x, y, contents) {
$('' + contents + '').css( {
position: 'absolute',
display: 'none',
top: y + 25,
left: x + 0,
border: '2px solid #777',
padding: '2px',
'font-family': 'Arial',
'font-size:': '1.2em',
'font-weight': 'bold',
'background-color': '#ddd',
opacity: 0.80
}).appendTo("body").fadeIn(200);
}
var previousPoint = null;
$("#placeholder").bind("plothover", function (event, pos, item) {
$("#x").text(pos.x.toFixed(2));
$("#y").text(pos.y.toFixed(2));
if (item) {
if (previousPoint != item.datapoint) {
previousPoint = item.datapoint;
$("#tooltip").remove();
var x = item.datapoint[0].toFixed(0),
y = item.datapoint[1].toFixed(2);
showTimes(x);
showTooltip(item.pageX, item.pageY,
y + "°C (at " + humanTime + "+1000)");
}
}
else {
$("#tooltip").remove();
previousPoint = null;
}
});
});
</script>
</head >
<body>
<?php
include('tempTesting.php');
?>
<div id="placeholder" style="height:300px;width=100px;"></div>
<div id="overview"></div>
<p>Flot Temperature realtime update. Below here is the Information</p>
</body>
</html>

Try var dat = "<?php echo $return; ?>"; instead.
Without quotes, if $return contains a string, javascript will interpret it as a variable, which is I think not the desired result.
Also, I you didn't set you server configuration to execute PHP in HTML files, this won't work since your file has a '.html' extension. Just rename your file to 'project.php' and it should be OK.

You cannot call PHP functions within a Javascript script. When the page loads, PHP is rendered first, followed by CSS and Javascript. So the line var dat = <?php echo $return;?>; wouldn't run properly.
Instead, you can use an Ajax request. Example here.
EDIT: Understood the question wrong. You cannot use PHP functions within a Javascript function dynamically. However, accessing just an echo command works.

Related

Php with json to power bi api

I have used this sample to connect to google Api for charts. It works great.
PHP MySQL Google Chart JSON - Complete Example
I am trying to get graphs and charts sample working with PowerBI.
I have sample.html file. I found this sample here:
https://github.com/Microsoft/PowerBI-visuals/wiki/Displaying-visuals-in-a-single-html-page
The file has reference to 1 css file and 2 javscript file on github.
It displays a blank page.
<link href="https://raw.githubusercontent.com/Microsoft/PowerBI-visuals/master/lib/visuals.css" rel="stylesheet">
<script type="text/javascript" src="externals.min.js"></script>
<script type="text/javascript" src="powerbi-visuals.js"></script>
<script type="text/javascript" src="https://raw.githubusercontent.com/Microsoft/PowerBI-visuals/master/lib/powerbi-visuals.js"> </script>
<script type="text/javascript" src="https://raw.githubusercontent.com/Microsoft/PowerBI-visuals/master/lib/powerbi-visuals.min.js"> </script>
<script type="text/javascript" src="https://github.com/Microsoft/PowerBI-visuals/blob/master/lib/powerbi-externals.d.ts"></script>
<style>
.visual {
'background-color' : 'white',
'padding' : '10px',
'margin' : '5px'
}
</style>
</head>
<body>
<script type="text/javascript">
var createDataView = function () {
var DataViewTransform = powerbi.data.DataViewTransform;
var fieldExpr = powerbi.data.SQExprBuilder.fieldExpr({ column: { entity: "table1", name: "country" } });
var categoryValues = ["Australia", "Canada", "France", "Germany", "United Kingdom", "United States"];
var categoryIdentities = categoryValues.map(function (value) {
var expr = powerbi.data.SQExprBuilder.equal(fieldExpr, powerbi.data.SQExprBuilder.text(value));
return powerbi.data.createDataViewScopeIdentity(expr);
});
// Metadata, describes the data columns, and provides the visual with hints
// so it can decide how to best represent the data
var dataViewMetadata = {
columns: [
{
displayName: 'Country',
queryName: 'Country',
type: powerbi.ValueType.fromDescriptor({ text: true })
},
{
displayName: 'Sales Amount (2014)',
isMeasure: true,
format: "$0",
queryName:'sales1',
type: powerbi.ValueType.fromDescriptor({ numeric: true }),
},
{
displayName: 'Sales Amount (2013)',
isMeasure: true,
format: "$0",
queryName:'sales2',
type: powerbi.ValueType.fromDescriptor({ numeric: true })
}
],
};
var columns = [
{
source: dataViewMetadata.columns[1],
// Sales Amount for 2014
values: [742731.43, 162066.43, 283085.78, 300263.49, 376074.57, 814724.34],
},
{
source: dataViewMetadata.columns[2],
// Sales Amount for 2013
values: [742731.43, 162066.43, 283085.78, 300263.49, 376074.57, 814724.34].reverse()
}
];
var dataValues = DataViewTransform.createValueColumns(columns);
var dataView = {
metadata: dataViewMetadata,
categorical: {
categories: [{
source: dataViewMetadata.columns[0],
values: categoryValues,
identity: categoryIdentities,
}],
values: dataValues
}
};
return dataView;
};
function createDefaultStyles(){
var dataColors = new powerbi.visuals.DataColorPalette();
return {
titleText: {
color: { value: 'rgba(51,51,51,1)' }
},
subTitleText: {
color: { value: 'rgba(145,145,145,1)' }
},
colorPalette: {
dataColors: dataColors,
},
labelText: {
color: {
value: 'rgba(51,51,51,1)',
},
fontSize: '11px'
},
isHighContrast: false,
};
}
function createVisual() {
var pluginService = powerbi.visuals.visualPluginFactory.create();
var defaultVisualHostServices = powerbi.visuals.defaultVisualHostServices;
var width = 600;
var height = 400;
var element = $('.visual');
element.height(height).width(width);
// Get a plugin
var visual = pluginService.getPlugin('columnChart').create();
powerbi.visuals.DefaultVisualHostServices.initialize();
visual.init({
// empty DOM element the visual should attach to.
element: element,
// host services
host: defaultVisualHostServices,
style: createDefaultStyles(),
viewport: {
height:height,
width: width
},
settings: { slicingEnabled: true },
interactivity: { isInteractiveLegend: false, selection: false },
animation: { transitionImmediate: true }
});
// Call update to draw the visual with some data
visual.update({
dataViews: [createDataView()] ,
viewport: {
height: height,
width: width
},
duration: 0
});
}
createVisual();
</script>
<div class="visual"></div>
</body>
</html>
The reference files are located at this location:
<script type="text/javascript" src="http://microsoft.github.io/PowerBI-visuals/playground/externals.min.js"> </script>
<script type="text/javascript" src="http://microsoft.github.io/PowerBI-visuals/playground/powerbi-visuals.js" ></script>
<script type="text/javascript" src="http://microsoft.github.io/PowerBI-visuals/playground/PowerBIVisualsPlayground.js"></script>
This is the full working script:
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link href="https://raw.githubusercontent.com/Microsoft/PowerBI-visuals/master/lib/visuals.css" rel="stylesheet">
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://microsoft.github.io/PowerBI-visuals/playground/externals.min.js"> </script>
<script type="text/javascript" src="http://microsoft.github.io/PowerBI-visuals/playground/powerbi-visuals.js" ></script>
<script type="text/javascript" src="http://microsoft.github.io/PowerBI-visuals/playground/PowerBIVisualsPlayground.js"></script>
<style>
.visual {
'background-color' : 'white',
'padding' : '10px',
'margin' : '5px'
}
</style>
</head>
<body>
<h1> hello </h1>
<div class="visual"></div>
<script type="text/javascript">
var createDataView = function () {
var DataViewTransform = powerbi.data.DataViewTransform;
var fieldExpr = powerbi.data.SQExprBuilder.fieldExpr({ column: { entity: "table1", name: "country" } });
var categoryValues = ["Australia", "Canada", "France", "Germany", "United Kingdom", "United States"];
var categoryIdentities = categoryValues.map(function (value) {
var expr = powerbi.data.SQExprBuilder.equal(fieldExpr, powerbi.data.SQExprBuilder.text(value));
return powerbi.data.createDataViewScopeIdentity(expr);
});
// Metadata, describes the data columns, and provides the visual with hints
// so it can decide how to best represent the data
var dataViewMetadata = {
columns: [
{
displayName: 'Country',
queryName: 'Country',
type: powerbi.ValueType.fromDescriptor({ text: true })
},
{
displayName: 'Sales Amount (2014)',
isMeasure: true,
format: "$0",
queryName:'sales1',
type: powerbi.ValueType.fromDescriptor({ numeric: true }),
},
{
displayName: 'Sales Amount (2013)',
isMeasure: true,
format: "$0",
queryName:'sales2',
type: powerbi.ValueType.fromDescriptor({ numeric: true })
}
],
};
var columns = [
{
source: dataViewMetadata.columns[1],
// Sales Amount for 2014
values: [742731.43, 162066.43, 283085.78, 300263.49, 376074.57, 814724.34],
},
{
source: dataViewMetadata.columns[2],
// Sales Amount for 2013
values: [742731.43, 162066.43, 283085.78, 300263.49, 376074.57, 814724.34].reverse()
}
];
var dataValues = DataViewTransform.createValueColumns(columns);
var dataView = {
metadata: dataViewMetadata,
categorical: {
categories: [{
source: dataViewMetadata.columns[0],
values: categoryValues,
identity: categoryIdentities,
}],
values: dataValues
}
};
return dataView;
};
function createDefaultStyles(){
var dataColors = new powerbi.visuals.DataColorPalette();
return {
titleText: {
color: { value: 'rgba(51,51,51,1)' }
},
subTitleText: {
color: { value: 'rgba(145,145,145,1)' }
},
colorPalette: {
dataColors: dataColors,
},
labelText: {
color: {
value: 'rgba(51,51,51,1)',
},
fontSize: '11px'
},
isHighContrast: false,
};
}
function createVisual() {
var pluginService = powerbi.visuals.visualPluginFactory.create();
var defaultVisualHostServices = powerbi.visuals.defaultVisualHostServices;
var width = 600;
var height = 400;
var element = $('.visual');
element.height(height).width(width);
// Get a plugin
var visual = pluginService.getPlugin('columnChart').create();
powerbi.visuals.DefaultVisualHostServices.initialize();
visual.init({
// empty DOM element the visual should attach to.
element: element,
// host services
host: defaultVisualHostServices,
style: createDefaultStyles(),
viewport: {
height:height,
width: width
},
settings: { slicingEnabled: true },
interactivity: { isInteractiveLegend: false, selection: false },
animation: { transitionImmediate: true }
});
// Call update to draw the visual with some data
visual.update({
dataViews: [createDataView()] ,
viewport: {
height: height,
width: width
},
duration: 0
});
}
createVisual();
</script>
</body>
</html>

highchart load the chart but not the JSON data

I'm trying to use highcharts to draw data from php json.
the php works ok but i dont know how to make the json an input.
Speciffically 'm trying to put the data on single Gauge Chart like the one on the example, but i can't configure the script to read the json.
The URL si this: php/KPItonsStock.php
<?php
function getArraySQL(){
$startd = "29964";
$endd = "29968";
$dsn = "prueba";
$connect = odbc_connect( $dsn, '', '' );
$query = "
Select SUM(TON_DESCARGADO) AS data
from
(Select unit,[load],enum_LOAD.[name],SUM(dumptons) as TON_DESCARGADO
from hist_dumps inner join hist_loclist on hist_dumps.shiftindex = hist_loclist.shiftindex
and hist_dumps.loc = hist_loclist.locid
inner join enum_LOAD on hist_dumps.[load] = enum_LOAD.[num]
where hist_dumps.shiftindex between '$startd' and '$endd'
GROUP BY loc,UNIT,unit#,[load],enum_LOAD.[name])TEMP1
where unit = 'Stockpile'
GROUP BY unit
order BY UNIT";
if(!$rs = odbc_exec($connect, $query)) die();
$rawdata = array();
$i=0;
while($row = odbc_fetch_array($rs))
{
$rawdata[$i] = $row;
$i++;
}
odbc_close( $connect );
return $rawdata;
};
$data = getArraySQL();
echo json_encode(($data), JSON_NUMERIC_CHECK);
and the result is this:
[{"data":29655.88482666}]
so i need to put information from that URL to the gauge chart.
Im trying with getjson, but I'm missing something, because the chart loads but not the data.
This is the otriginal highchart example
http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/gauge-solid/
This is the example with my data
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.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.js"></script>
<style type="text/css">
${demo.css}
</style>
<script type="text/javascript">
function visitorData (data) {
$('#container').highcharts({
chart: {
type: 'solidgauge'
},
title: {
text: 'Average Visitors'
},
pane: {
center: ['50%', '85%'],
size: '140%',
startAngle: -90,
endAngle: 90,
background: {
backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || '#EEE',
innerRadius: '60%',
outerRadius: '100%',
shape: 'arc'
}
},
yAxis: {
min: 0,
max: 40000,
title: {
text: 'Speed'},
stops: [
[0.1, '#55BF3B'], // green
[0.5, '#DDDF0D'], // yellow
[0.9, '#DF5353'] // red
],
lineWidth: 0,
minorTickInterval: null,
tickPixelInterval: 400,
tickWidth: 0,
title: {
y: -70
},
labels: {
y: 16
}
},
series: data,
});
}
$(document).ready(function() {
$.ajax({
url: 'report2/KPItonsStock.php',
type: 'GET',
async: true,
dataType: "json",
success: function (data) {
visitorData(data);
}
});
});
</script>
</head>
<body>
<div style="width: 600px; height: 400px; margin: 0 auto">
<div id="container" style="width: 300px; height: 200px; float: left"></div>
</div>
</body>
</html>
I get the graphic but it doesnt load any data
Data needs to be an array. Make your backend return
[{
"data": [29655.88482666]
}]
http://jsfiddle.net/nicholasduffy/openzant/3/

highcharts not displaying graph

im trying to print results stored in my database using php and highcharts api.but the graph doesnt show on the screen.not even the axis get displayed.the data is got from a mysql database.i tries using the same code as in the highcharts demo but no luck.heres my code
<?php
require_once ('connection.php');
session_start();
$username = $_SESSION['username'];
$quizes=null;
$score=array();
$i=0;
$result = mysql_query("SELECT * FROM `score` WHERE `username`='$username'") or die(mysql_error);
while($rows=mysql_fetch_array($result)) {
$quizes= $quizes. "'".$rows['quiz']."',";
$score[$i]=$rows['score'];
$i=$i+1;
}
print_r($score);
echo $quizes;
?>
<html>
<body>
<script src="js/jquery.js"></script>
<script src="highcharts/js/highcharts.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//passing php variables to javascript variables
//eg var mk1=<?php echo $mark1 ?>;
var mk1=<?php echo $score[1] ?>;
var mk2=<?php echo $score[2] ?>;
var mk3=<?php echo $score[3] ?>;
var mk4=<?php echo $score[4] ?>;
var mk5=<?php echo $score[5] ?>;
var mk6=<?php echo $score[6] ?>;
var mk7=<?php echo $score[7] ?>;
var mk8=<?php echo $score[8] ?>;
var chart1 = new Highcharts.Chart({
chart: {
renderTo: 'graphDiv',
defaultSeriesType: 'column'
},
title: {
text: 'SEMESTER'
},
xAxis: {
categories: ['QUIZ A', 'QUIZ B', 'QUIZ C', 'QUIZ D', 'QUIZ E', 'QUIZ F','QUIZ G','QUIZ H']
},
yAxis: {
title: {
text: 'Percentage'
}
},
series: [{
name: ['Quiz Progress'],
data: [mk1, mk2, mk3, mk4, mk5, mk6, mk7, mk8]
},]
});
});
</script>
<div id="graphDiv" style="width: 700px; height: 400px; float: left"></div>
</body>
</html>
Here is example to get data from mysql database in highchart.
Lest start with
Index.php
<head>
<meta name="Gopal Joshi" content="Highchart with Mysql" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Highchart with Mysql Database</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/setup.js"></script>
<script type="text/javascript" src="js/test.js"></script>
</head>
<body>
<script src="js/highcharts.js"></script>
<div id="sales" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
</body>
setup.js
var chart;
$(document).ready(function() {
var cursan = {
chart: {
renderTo: 'sales',
defaultSeriesType: 'area',
marginRight: 10,
marginBottom: 20
},
title: {
text: 'Highchart With Mysql',
},
subtitle: {
text: 'www.spjoshis.blogspot.com',
},
xAxis: {
categories: ['Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar']
},
yAxis: {
title: {
text: 'Average'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
crosshairs: true,
shared: true
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 30,
borderWidth: 0
},
plotOptions: {
series: {
cursor: 'pointer',
marker: {
lineWidth: 1
}
}
},
series: [{
color: Highcharts.getOptions().colors[2],
name: 'Test Colomn',
marker: {
fillColor: '#FFFFFF',
lineWidth: 3,
lineColor: null // inherit from series
},
dataLabels: {
enabled: true,
rotation: 0,
color: '#666666',
align: 'top',
x: -10,
y: -10,
style: {
fontSize: '9px',
fontFamily: 'Verdana, sans-serif',
textShadow: '0 0 0px black'
}
}
}],
}
//Fetch MySql Records
jQuery.get('js/data.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 = line[0] ;
amo=parseFloat(line[1].replace(',', ''));
if (isNaN(amo)) {
amo = null;
}
traffic.push([
date,
amo
]);
});
} catch (e) { }
cursan.series[0].data = traffic;
chart = new Highcharts.Chart(cursan);
});
});
Here js will import data from mysql using data.php file and supply it to our chart
data.php
$con=mysql_connect('localhost','root','');
mysql_select_db("test", $con);
$result=mysql_query('select * from sales order by id');
while($row = mysql_fetch_array($result)) {
echo $row['month'] . "\t" . $row['amount']. "\n";
}
data.php will simply print value on page that we will use for chart.
You can use this method with multiple charts on same page and no more files will required for more then single chart.
It will output like
Click Here for more help or Download example.
I think your getting data in string format. convert data to integer like this way,
var mk1=<?php echo $score[1] ?>;
to integer: +mk1 // and check typeof +mk1
Here is the demo http://jsfiddle.net/XF293/
I advice to consider use json_encode() in php and return all values as single array. Then use $.getJSON() to avoid problems with printing values. As a result how your data looks like? I mean in javascript.

Multiple series, multiple charts Highcharts

i have to create a single chart showing different series with different type of chart (Ex: one data series with 'areaspline' and one data series with 'column'). I built a db with a lot of data, extracted by sql query into a json file
[
{ "name": "Test", "data": [2.8,2.8,2.8,2.7,2.7,] },
{ "name": "kwc", "data": [10,1,10,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] }
]
The json file is correct, but if i try to select the series for a chart with the $.each function it doesn't work!
Here's my code
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script src="estrazione.php"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$.getJSON("new3.php", function(json) {
$.each(json.data, function(index, item){
// split the data set into ohlc and volume
var temperatura = [],
misura = [],
dataLength = json.length;
for (i = 0; i < dataLength; i++) {
temperatura.push([
data[i][0]
]);
misura.push([
data[i][1]
])
}
$('#container').highcharts({
chart: {
zoomType: 'xy'
},
title: {
text: 'Analisi Temperature e Consumo Generale',
},
xAxis: [{
categories: ['00.00', '00.15', '00.30', '00.45', '01.00', '01.15', '01.30', '01.45', '02.00', '02.15', '02.30', '02.45', '03.00', '03.15', '03.30', '03.45', '04.00', '04.15', '04.30', '04.45', '05.00', '05.15', '05.30', '05.45', '06.00', '06.15', '06.30', '06.45', '07.00', '07.15', '07.30', '07.45', '08.00', '08.15', '08.30', '08.45', '09.00', '09.15', '09.30', '09.45', '10.00', '10.15', '10.30', '10.45', '11.00', '11.15', '11.30', '11.45', '12.00', '12.15', '12.30', '12.45', '13.00', '13.15', '13.30', '13.45', '14.00', '14.15', '14.30', '14.45', '15.00', '15.15', '15.30', '15.45', '16.00', '16.15', '16.30', '16.45', '17.00', '17.15', '17.30', '17.45', '18.00', '18.15', '18.30', '18.45', '19.00', '19.15', '19.30', '19.45', '20.00', '20.15', '20.30', '20.45', '21.00', '21.15', '21.30', '21.45', '22.00', '22.15', '22.30', '22.45', '23.00', '23.15', '23.30', '23.45'],
}],
yAxis: [{ // Primary yAxis
labels: {
format: '{value}°C',
style: {
color: '#89A54E'
}
},
title: {
text: 'Temperature',
style: {
color: '#89A54E'
}
}
}, { // Secondary yAxis
title: {
text: 'Consumo',
style: {
color: '#4572A7'
}
},
labels: {
format: '{value} Kw',
style: {
color: '#4572A7'
}
},
opposite: true
}],
tooltip: {
shared: true
},
legend: {
layout: 'vertical',
align: 'left',
x: 120,
verticalAlign: 'top',
y: 100,
floating: true,
backgroundColor: '#FFFFFF'
},
series: [{
name: 'Misure',
color: '#4572A7',
type: 'column',
yAxis: 1,
data: misura,
tooltip: {
valueSuffix: ' Kw'
}
}, {
name: 'Temperature',
color: '#89A54E',
type: 'spline',
data: temperatura,
tooltip: {
valueSuffix: '°C'
}
}]
});
});
</script>
</head>
<body>
<script src="js/highcharts.js"></script>
<script src="js/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
</body>
</html>'
this is my php code:
<?php
$data_scelta = "2013-08-08";
$misura = "kwc";
$temperatura = "Test";
$link = mysqli_connect('localhost:3306', 'root', '','telegestione');
if (!$link) {
die('Could not connect: ' . mysqli_error());}
$sth = mysqli_query($link,"SELECT $temperatura FROM temperature WHERE dataora BETWEEN '$data_scelta 00:00:00.000'
AND '$data_scelta 23:59:59.997'");
$rows = array();
$rows['name'] = $temperatura;
while($r = mysqli_fetch_assoc($sth)) {
$rows['data'][] = $r[$temperatura];}
$sth = mysqli_query($link,"SELECT $misura FROM misure WHERE dataora BETWEEN '$data_scelta 00:00:00.000'
AND '$data_scelta 23:59:59.997'");
$rows1 = array();
$rows1['name'] = $misura;
while($rr = mysqli_fetch_assoc($sth)) {
$rows1['data'][] = $rr[$misura];}
$result = array();
array_push($result,$rows);
array_push($result,$rows1);
print json_encode($result, JSON_NUMERIC_CHECK);
?>
I tryed any kind of option, but anything gone right :(
Any hope to display 1 chart, 2 or more data series and 2 or more type of charts?
Thanks in advance
It looks like your highcharts creation call is within your $.each function. So it will try to create 2 highcharts, but they both will be created in the same div, so you'll only end up with one.
Also, the way you are caculating datalength, it'll be 2. When, it appears, you'd like it to be the length of the actual data (which is different for your different series).
I can't do the getJSON in a jsfiddle, so I'm assuming your PHP code is creating the json object you listed (and it looks like it would). You can lose the each loop alltogether and set your 2 series like this:
series: [{
name: 'Misure',
color: '#4572A7',
type: 'column',
yAxis: 1,
data: json[1].data,
tooltip: {
valueSuffix: ' Kw'
}
}, {
name: 'Temperature',
color: '#89A54E',
type: 'spline',
data: json[0].data,
tooltip: {
valueSuffix: '°C'
}
}]
http://jsfiddle.net/bhlaird/dUkuY/

Data won't echo on Highcharts

I can't get my data to plot on the highchart but it shows up on the source, what am I doing wrong? I don't know if I am using the wrong syntax to echo my string from the hcdata.php. I have been having this problem with getting the output to show up on the actual chart from what I can see the data is correctly formatted it comes out like this:
[Date.UTC(2013,05,31,10,39,36), 20179],
[Date.UTC(2013,05,31,10,30,00), 20031],
[Date.UTC(2013,05,31,10,09,36), 19684],
[Date.UTC(2013,05,31,09,54,36), 19384],
[Date.UTC(2013,05,31,09,39,36), 19039],
[Date.UTC(2013,05,31,09,24,36), 18763],
[Date.UTC(2013,05,31,09,09,36), 18435],
[Date.UTC(2013,05,31,08,54,36), 18097],
[Date.UTC(2013,05,31,08,39,36), 17788],
[Date.UTC(2013,05,31,08,30,00), 17552],
[Date.UTC(2013,05,31,08,09,36), 17169],
[Date.UTC(2013,05,31,08,00,00), 16940],
[Date.UTC(2013,05,31,07,45,00), 16608],
[Date.UTC(2013,05,31,07,30,00), 16284],
[Date.UTC(2013,05,31,07,15,00), 15922],
[Date.UTC(2013,05,31,06,54,36), 15216],
[Date.UTC(2013,05,31,06,39,36), 14724],
[Date.UTC(2013,05,31,06,30,00), 14352],
[Date.UTC(2013,05,31,06,09,36), 13713],
[Date.UTC(2013,05,31,05,54,36), 13491],
[Date.UTC(2013,05,31,05,39,36), 13660],
[Date.UTC(2013,05,31,05,24,36), 13680],
[Date.UTC(2013,05,31,05,09,36), 13548],
[Date.UTC(2013,05,31,04,54,36), 13327],
[Date.UTC(2013,05,31,04,45,00), 13263],
[Date.UTC(2013,05,31,04,30,00), 13178],
[Date.UTC(2013,05,31,04,09,36), 13105],
[Date.UTC(2013,05,31,03,54,36), 13048],
[Date.UTC(2013,05,31,03,39,36), 13054],
[Date.UTC(2013,05,31,03,24,36), 13079],
[Date.UTC(2013,05,31,03,15,00), 13138],
[Date.UTC(2013,05,31,03,00,00), 13200],
[Date.UTC(2013,05,31,02,39,36), 13330],
[Date.UTC(2013,05,31,02,24,36), 13409],
[Date.UTC(2013,05,31,02,15,00), 13512],
[Date.UTC(2013,05,31,01,54,36), 13675],
[Date.UTC(2013,05,31,01,39,36), 13825],
[Date.UTC(2013,05,31,01,24,36), 13986],
[Date.UTC(2013,05,31,01,15,00), 14143],
[Date.UTC(2013,05,31,00,54,36), 13851],
[Date.UTC(2013,05,31,00,39,36), 14066],
[Date.UTC(2013,05,31,00,24,36), 14303],
[Date.UTC(2013,05,31,00,09,36), 14591]
<?php include "data.php"; ?>
<?php include "hcdata.php"; ?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></title>
<script type="text/javascript" src="''/SQLPHP/js/jquery.min.js"></script>
<script src="''/SQLPHP/js/highcharts.js"></script>
<script src="''/SQLPHP/js/modules/exporting.js"></script>
<script type="text/javascript">
$(function () {
var data = [
[<?php echo $finalString; ?>]
];
data.sort(function(a,b) {
return a[0] - b[0];
});
$('#container').highcharts({
chart: {
type: 'spline'
},
title: {
text: 'Forecast vs Actual Load [VM]'
},
subtitle: {
text: 'This chart displays the time and actual forecast load for this region'
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: { // don't display the dummy year
month: '%e. %b',
year: '%b'
}
},
yAxis: {
title: {
text: 'Actual Load (WM)'
},
min: 0
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
Highcharts.dateFormat('%e. %b', this.x) +': '+ this.y +' m';
}
},
series: [{
name: 'Forecast vs Actual Load',
// Define the data points. All series have a dummy year
// of 1970/71 in order to be compared on the same x axis. Note
// that in JavaScript, months start at 0 for January, 1 for February etc.
data: data
}]
});
});
</script>
</head>
<body>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
Your PHP data insert looks like it is wrapping the data in 2 [] blocks:
var data = [
[<?php echo $finalString; ?>]
];
You need to wrap your entire data set in one []. Such that it looks like:
var data = [
<?php echo $finalString; ?>
];
You should end up with this:
[
[Date.UTC(2013,05,31,10,39,36), 20179], [Date.UTC(2013,05,31,10,30,00), 20031], [Date.UTC(2013,05,31,10,09,36), 19684], [Date.UTC(2013,05,31,09,54,36), 19384], [Date.UTC(2013,05,31,09,39,36), 19039], [Date.UTC(2013,05,31,09,24,36), 18763], [Date.UTC(2013,05,31,09,09,36), 18435], [Date.UTC(2013,05,31,08,54,36), 18097], [Date.UTC(2013,05,31,08,39,36), 17788], [Date.UTC(2013,05,31,08,30,00), 17552], [Date.UTC(2013,05,31,08,09,36), 17169], [Date.UTC(2013,05,31,08,00,00), 16940], [Date.UTC(2013,05,31,07,45,00), 16608], [Date.UTC(2013,05,31,07,30,00), 16284], [Date.UTC(2013,05,31,07,15,00), 15922], [Date.UTC(2013,05,31,06,54,36), 15216], [Date.UTC(2013,05,31,06,39,36), 14724], [Date.UTC(2013,05,31,06,30,00), 14352], [Date.UTC(2013,05,31,06,09,36), 13713], [Date.UTC(2013,05,31,05,54,36), 13491], [Date.UTC(2013,05,31,05,39,36), 13660], [Date.UTC(2013,05,31,05,24,36), 13680], [Date.UTC(2013,05,31,05,09,36), 13548], [Date.UTC(2013,05,31,04,54,36), 13327], [Date.UTC(2013,05,31,04,45,00), 13263], [Date.UTC(2013,05,31,04,30,00), 13178], [Date.UTC(2013,05,31,04,09,36), 13105], [Date.UTC(2013,05,31,03,54,36), 13048], [Date.UTC(2013,05,31,03,39,36), 13054], [Date.UTC(2013,05,31,03,24,36), 13079], [Date.UTC(2013,05,31,03,15,00), 13138], [Date.UTC(2013,05,31,03,00,00), 13200], [Date.UTC(2013,05,31,02,39,36), 13330], [Date.UTC(2013,05,31,02,24,36), 13409], [Date.UTC(2013,05,31,02,15,00), 13512], [Date.UTC(2013,05,31,01,54,36), 13675], [Date.UTC(2013,05,31,01,39,36), 13825], [Date.UTC(2013,05,31,01,24,36), 13986], [Date.UTC(2013,05,31,01,15,00), 14143], [Date.UTC(2013,05,31,00,54,36), 13851], [Date.UTC(2013,05,31,00,39,36), 14066], [Date.UTC(2013,05,31,00,24,36), 14303], [Date.UTC(2013,05,31,00,09,36), 14591]
]

Categories