Hey guys I am having trouble loading my data into the highstock charts.
My json.php calls on a sample MySQL database and looks something like this:
$result = mysql_query("SELECT UNIX_TIMESTAMP(date)*1000 AS timestamp,value from sample") or die('Could not query');
if(mysql_num_rows($result)){
echo 'Test';
$first = true;
$row=mysql_fetch_assoc($result);
while($row=mysql_fetch_row($result)){
if($first) {
$first = false;
} else {
echo ',';
}
$json_str = json_encode($row, JSON_NUMERIC_CHECK);
echo $json_str;
}
if(array_key_exists('callback', $_GET)){
$callback = $_GET['callback'];
echo $callback. '('.$json_str.');';
}
} else {
echo '[]';
}
mysql_close($db);
My index.htm which calls the Json.php is from the sample highstock template I just merely changed the getJson to match with my reference. Here is the code. Any help would be much appreciated, thanks.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highstock Example</title>
<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('json.php', function(data) {
// Create the chart
$('#container').highcharts('StockChart', {
rangeSelector : {
selected : 1
},
title : {
text : 'Test'
},
series : [{
name : 'Test',
data : data,
marker : {
enabled : true,
radius : 3
},
shadow : true,
tooltip : {
valueDecimals : 2
}
}]
});
});
});
</script>
</head>
<body>
<script src="js/highstock.js"></script>
<script src="js/modules/exporting.js"></script>
<div id="container" style="height: 500px; min-width: 500px"></div>
</body>
</html>
Also, my json is parsed in this manner:
Test[1370899026000,10],[1370899026000,4],[1368177426000,11],[1370899026000,12],[1370899026000,13],[1370899026000,11],[1370899026000,13],[1370899026000,11],[1370899026000,13],[1370899026000,9],[1370899026000,14],[1370899026000,12],[1370899026000,10],[1370899026000,15],[1370899026000,12],[1378826226000,7],[1370899026000,9],[1370899026000,11],[1370899026000,7],[1370899026000,3],[1370899026000,6],[1370899026000,0],[1370899026000,11],[1370899026000,5],[1370899026000,9],[1370899026000,7],[1370899026000,8],[1370899026000,8],[1370899026000,9],[1370899026000,13],[1370899026000,11],[1370899026000,10],[1370899026000,13],[1370899026000,12],[1370899026000,12],[1370899026000,11],[1370899026000,13],[1370899026000,10],[1370899026000,8],[1370899026000,15],[1370899026000,13],[1370899026000,12],[1370899026000,14],[1370899026000,9],[1370899026000,9],[1370899026000,12],[1370899026000,13],[1370899026000,4],[1370899026000,4],[1370899026000,4],[1370899026000,13],[1370899026000,5],[1370899026000,10],[1370899026000,4],[1370899026000,10],[1370899026000,22],[1370899026000,9],[1370899026000,5],[1370899026000,9],[1370899026000,10],[1370899026000,5],[1370899026000,7],[1370899026000,10],[1370899026000,5],[1370899026000,7],[1370899026000,9],[1370899026000,9],[1370899026000,10],[1370899026000,6],[1370899026000,6],[1370899026000,6],[1370899026000,12],[1370899026000,7],[1370899026000,12],[1370899026000,8],[1370899026000,13],[1370899026000,12],[1370899026000,9],[1370899026000,7],[1370899026000,7],[1370899026000,9],[1370899026000,12],[1370899026000,13],[1370899026000,9],[1370899026000,10],[1370899026000,4],[1370899026000,11],[1370899026000,12],[1370899026000,13],[1370899026000,11],[1370899026000,13],[1370899026000,11],[1370899026000,13],[1370899026000,9],[1370899026000,14],[1370899026000,12],[1370899026000,10],[1370899026000,15],[1370899026000,12],[1370899026000,7],[1370899026000,9],[1370899026000,11],[1370899026000,7],[1370899026000,3],[1370899026000,6],[1370899026000,0],[1370899026000,11],[1370899026000,5],[1370899026000,9],[1370899026000,7],[1370899026000,8],[1370899026000,8],[1370899026000,9],[1370899026000,13],[1370899026000,11],[1370899026000,10],[1370899026000,13],[1370899026000,12],[1370899026000,12],[1370899026000,11],[1370899026000,13],[1370899026000,10],[1370899026000,8],[1370899026000,15],[1370899026000,13],[1370899026000,12],[1370899026000,14],[1370899026000,9],[1370899026000,9],[1370899026000,12],[1370899026000,13],[1370899026000,4],[1370899026000,4],[1370899026000,4],[1370899026000,13],[1370899026000,5],[1370899026000,10],[1370899026000,4],[1370899026000,10],[1370899026000,22],[1370899026000,9],[1370899026000,5],[1370899026000,9],[1370899026000,10],[1370899026000,5],[1370899026000,7]
Try closing with
[]
Highstock fiddle: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/stock/demo/areaspline/
Data of that fiddle: http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?
Please take look at http://docs.highcharts.com/#preprocessing-data-from-a-database and take look at very simple example with json_encode:
tmp = array();
$tmp[] = array('A',5);
$tmp[] = array('B',6);
$tmp[] = array('C',1);
$tmp[] = array('D',2);
$rows = array();
for($i=0; $i<count($tmp); $i++)
{
$row['name'] = $tmp[$i][0];
$row['data'] = array($tmp[$i][1]);
array_push($rows,$row);
}
print json_encode($rows);
Highcharts:
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
series: [{
name: 'Browser share',
data: []
}]
}
$.getJSON("datavotecolum.php", function(json) {
console.log(json);
options.series = json;
chart = new Highcharts.Chart(options,function(chart){
console.log(chart.series);
});
});
});
I am trying to set a variable $id=$_GET["categoryID"]. I cannot get it to work. I believe it has to do with the the Ajax request. But I don't know how I have to format it so that it will work in conjunction with that request. I need the variable for a mysql query. Any help is greatly appreciated. This is over my head and have been struggling with it for days. I have tried both GET and POST. Thanks.
I have distilled the page down to this...
<!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>Test $_GET</title>
</head>
<body>
<?php
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$id = $_GET["categoryID"];
//$id=3;
}
?>
print_r($_GET) = <?php print_r($_GET); ?>
<br />
print_r($id) = <?php print_r($id); ?>
</body>
</html>
Here is the resulting page....
<!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>Test $_GET</title>
</head>
<body>
print_r($_GET) = Array
(
[categoryID] => 1001
)
<br />
print_r($id) =
</body>
</html>
Here is the whole page....
<?php
if (#$_REQUEST['ajax']) {
$link = $nm33;
if ($link == false)
trigger_error('Connect failed - ' . mysql_error(), E_USER_ERROR);
$connected = mysql_select_db('nm', $link);
if ($connected) {
//How do I set $id = $_GET["categoryID"] It fails to set the variable.
$id =$_GET["categoryID"];
// $id=1;
// It will work as $id=1
$results = mysql_query('select * from selectMenu where categoryID= \'' . $id . '\' AND category="' . strtolower(mysql_real_escape_string(strip_tags($_REQUEST['category']))) . '"');
//////////
$json = array();
while (is_resource($results) && $row = mysql_fetch_object($results)) {
//$json[] = '{"id" : "' . $row->id . '", "label" : "' . $row->label . '"}';
$json[] = '"' . $row->label . '"';
}
echo '[' . implode(',', $json) . ']';
die(); // filthy exit, but does fine for our example.
} else {
user_error("Failed to select the database");
}
}
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="js/select-chain.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
<!--
$(function () {
var cat = $('#categorySelect');
var el = $('#elementSelect');
var attr = $('#attributeSelect');
el.selectChain({
target: attr,
url: 'select-menu.php',
data: { ajax: true, anotherval: "anotherAction" }
});
// note that we're assigning in reverse order
// to allow the chaining change trigger to work
cat.selectChain({
target: el,
url: 'select-menu.php',
data: { ajax: true }
}).trigger('change');
});
//-->
</script>
<link href="selectMenu.css" rel="stylesheet" type="text/css" />
<form action="performance-models.php" method="get">
<select name="category" class="dropdown" id="categorySelect">
<option selected="selected">Select Your Vehicle</option>
<?php do { ?>
<option> <?php echo $row_rsMake['make']; ?></option>
<?php } while ($row_rsMake = mysql_fetch_assoc($rsMake)); ?>
</select>
<select name="model" class="dropdown" id="elementSelect">
<option selected="selected">Select Model</option>
<option>[none selected]</option>
</select>
<select name="appYear" class="dropdown" id="attributeSelect" >
<option selected="selected"> </option>
<option>[none selected]</option>
</select>
<input type="submit" value="Go">
</form>
<p><br />
<br />
print_r($_GET) = <?php print_r($_GET); ?> <br />
print_r($_REQUEST) = <?php print_r($_REQUEST); ?><br />
echo $_REQUEST['categoryID'] <?php echo $_REQUEST['categoryID'];?>
</p>
Here is select-chain.js
(function ($) {
$.fn.selectChain = function (options) {
var defaults = {
key: "id",
value: "label"
};
var settings = $.extend({}, defaults, options);
if (!(settings.target instanceof $)) settings.target = $(settings.target);
return this.each(function () {
var $$ = $(this);
$$.change(function () {
var data = null;
if (typeof settings.data == 'string') {
data = settings.data + '&' + this.name + '=' + $$.val();
} else if (typeof settings.data == 'object') {
data = settings.data;
data['category'] = $$.val();
data['model'] = $$.val();
data['year'] = $$.val();
}
settings.target.empty();
$.ajax({
url: settings.url,
data: data,
type: (settings.type || 'get'),
dataType: 'json',
success: function (j) {
var options = [], i = 0, o = null;
for (i = 0; i < j.length; i++) {
// required to get around IE bug (http://support.microsoft.com/?scid=kb%3Ben-us%3B276228)
o = document.createElement("OPTION");
o.value = typeof j[i] == 'object' ? j[i][settings.key] : j[i];
o.text = typeof j[i] == 'object' ? j[i][settings.value] : j[i];
settings.target.get(0).options[i] = o;
}
// hand control back to browser for a moment
setTimeout(function () {
settings.target
.find('option:first')
.attr('selected', 'selected')
.parent('select')
.trigger('change');
}, 0);
},
error: function (xhr, desc, er) {
// add whatever debug you want here.
alert("an error occurred here");
}
});
});
});
};
})(jQuery);
A $_GET parameter is passed in the URL so for this;
http://www.google.com/?q=search
The parameter $_GET['q'] would be equal to 'search'
So when you perform your AJAX request you need to specify the parameters in the URL.
EDIT:
Try getting rid of your HTTP_X_REQUESTED_WITH statements. The request is probably safe enough without those kind of checks. Just simplify it to:
if ( isset( $_GET["categoryID"] ) ) {
$id = $_GET["categoryID"];
}
There is no need for:
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
You can just use:
$id = isset($_GET["categoryID"]) ? intval($_GET["categoryID"]) : 0;
Which is the same as (but shorter...):
if (isset($_GET["categoryID"]))
{
$id = intval($_GET["categoryID"]);
}
else
{
$id = 0;
}
If you want to check if a request was made via ajax, you would have to rewrite your script as the whole header section would not be needed. Instead you could call this script from your page, set a variable in the page itself and if that variable is not set in the script, it's an ajax call. Obviously this is just a simple example.
Edit: The plugin does not mention what the default type of the request is, but that could very well be POST so you could try to add type: "post" to the options of selectChain.
And to make sure that your response is well-formed json (when you get there...) I would also recommend you use json_encode, so:
echo json_encode($json);
die(); // filthy exit, but does fine for our example.
Edit 2: I just noticed another problem: Nowhere is the categoryID being added to the data section in the ajax:
You are requesting / posting to (???) : select-menu.php (notice, no query string!)
The data you are sending is: { ajax: true, anotherval: "anotherAction" } or { ajax: true}
So there is no way that categoryID is ever going to show up in select-menu.php.
The most logical thing to do, would be to add the selected category to the data section:
data: { "ajax": true, "anotherval": "anotherAction", "categoryID": cat }
and:
data: { "ajax": true, "categoryID": cat }
With jQuery you can use jQuery.get() or add a type='GET' parameter to jQuery.ajax(). Some example:
jQuery(function($) {
$.ajax({
url : 'your-page.php',
type : 'GET',
data : {
'paramName' => 'paramValue',
'foo' => 'bar'
},
success : function(data) {
// do something in the callback function
}
});
});
You need to pass the value in the jQuery.get():
$.get('yourphppage.php', { categoryID : 1234 }, function(data) {
alert(data);
});
In your php just echo right back your cateogryId to see if it is working
<?php echo $_GET['categorID'] ?>
I think this is a case of me not knowing javascript, but I can't for the love of god get this to work
For some reason, creating vars cancels out my java alert code. (maybe bc its wrong)
And my java vars aren't being set correctly.
I pointed out the problems in my comments
In my SQL, I have Temperatures all with an associative value disk 'id'.
So my data structure in this is:
$array[id];
$array[id]=array();
//For every new element
//Using while ($row = mysql_fetch_assoc($result))
$array[id][]="temperature";
//second id
$array[id2];
$array[id2]=array();
//For every new element
$array[id2][]="temperature";
$array[id2][]="temperature2";
$array[id2][]="temperature3";
$array[id2][]="temperature4";
MY ATTEMPT (WRONG CODE):
//I simplified this code down. In my own version, the join works ONLY when I use an actual index "174" instead of a javascript variable that is 174. Couldnt get join to be alerted in this simplified version
<?php
$phparray=array();
$phparray["100"]="First Element";
$phparray["101"]="Second Element";
$phparray["102"]="Third Element";
$phparray["100"]=array();
$phparray["101"]=array();
$phparray["100"][]="First Element - Sub 2";
$phparray["100"][]="First Element - Sub 3";
$phparray["101"][]="Second Element - Sub 2";
echo $phparray["100"]; //Does not show 'First Element'. Shows Array
echo $phparray["100"][0]; //Correctly shows sub element
//var_dump($phparray);
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Associative Array in PHP used in Java Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
var index=100;
//var index2=<?php echo $phparray[index]; ?>; //Supposed to output 'First Element'
var joined=[<?php echo join($phparray[index], ', '); ?>]; //Supposed to join elements of '100'
alert("hello"); //This line does not work anymore after the var index2 made above
</script>
</head>
<body>
<div id="container" style="height: 500px; min-width: 600px"></div>
</body>
</html>
EDIT: Here is the long full code of my php page:
<?php
include_once("../../config.php");
$conn=mysql_connect($dbhost,$dbuser,$dbpasswd) or die ('Error connecting to mysql');
mysql_select_db($dbname);
ini_set('error_reporting', E_ALL);
//ini_set('display_errors',1);
ini_set('log_errors',1);
$sql = "select disk_id from disk";
$result = mysql_query($sql);
$ids = array();
$names=array();
$temperatures = array();
while ($row = mysql_fetch_assoc($result)) {
$ids[] = $row['disk_id'];
$temperatures[]=$row['disk_id'];
//echo "<br>".$row['disk_id'];
}
//
foreach ($ids as $value)
{
//echo "--START ".$value."--<br>";
$sql = "select * from disk_data WHERE disk_id=".$value;
$result = mysql_query($sql);
$dates=array();
$key = array_search($value, $temperatures);
$temperatures[$value] = array();
//var_dump($temperatures);
while ($row = mysql_fetch_assoc($result))
{
$temps = $row['Temperature'];
$temp = explode("||", $temps);
$prehex=$temp[3];
$posthex=hexdec(substr($prehex,-2));
$predate=$row['create_date'];
$postdate =strtotime($predate)*1000;
$output="[".$postdate.", ".$posthex."]";
//$temperatures[$key][] = $output;
$temperatures[$value][] = $output;
$dates[]=$row['create_date'];
//echo $row['create_date']." ".end($temperatures[$key])."<br>";
}
}
print_r(array_keys($array));
var_dump($temperatures);
foreach ($ids as $value)
{
//echo $value;
$key = array_search($value, $temperatures);
//echo "Key: $key; Value: $temperatures[$value]<br />\n";
$comma = join($temperatures[$value],", ");
echo $comma;
echo "\n";
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highstock Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var seriesOptions = [],
yAxisOptions = [],
seriesCounter = 0,
//names=[<?php echo join($ids, ', '); ?>],
names=["174"], //Above code works. BUT only using ID 174 to test
values=[<?php echo join($temperatures["174"], ', '); ?>], //Supposed to be ALL data. But temp 174
colors = Highcharts.getOptions().colors;
//alert(values);
$.each(names, function(i, name2) {
//alert(seriesOptions.length);
alert(name2.toString()); //Works....
var values=[<?php
echo join($temperatures[name2], ', '); ?>]; //Doesnt work
//alert(values);
console.log(values);
//document.write(values);
seriesOptions[i] =
{
name: name2,
data:values
};
// As we're loading the data asynchronously, we don't know what order it will arrive. So
// we keep a counter and create the chart when all the data is loaded.
seriesCounter++;
if (seriesCounter == names.length)
{
createChart();
}
});
// create the chart when all data is loaded
function createChart() {
chart = new Highcharts.StockChart({
chart: {
renderTo: 'container'
},
rangeSelector: {
selected: 0
},
title: {
text: 'Test Performance Data',
style: {
margin: '10px 100px 0 0' // center it
}
},
yAxis: {
title: {text:'Temperature (°C)'},
labels: {
formatter: function() {
return this.value + '';
}
},
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},
plotOptions: {
line: {
gapSize: 0
},
series: {
//compare: 'percent'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
yDecimals: 2
},
series: seriesOptions
});
}
});
</script>
</head>
<body>
<script type="text/javascript" src="../js/highstock.js"></script>
<script type="text/javascript" src="../js/themes/gray.js"></script>
<div id="container" style="height: 500px; min-width: 600px"></div>
</body>
</html>
You cannot mix PHP and JavaScript like that. JavaScript variables are not parsed in PHP.
Even when index is replaced by a variable $index or 100, your code would still miss quotes.
Use the following instead:
<script type="text/javascript">
var index=100;
var array = <?php echo json_encode($phparray); ?>;
var joined = array[index];
The last line outputs the following:
var joined={"100":["First Element - Sub 2","First Element - Sub 3"],"101":["Second Element - Sub 2"],"102":"Third Element"};
Before trying this, make sure that you remove the invalid comment in the line after var index = 100;. Otherwise, a PHP warning can be generated, which invalidates the code:
var index=100;
//var index2=PHP Notice: Use of undefined constant index - assumed 'index' in /tmp/t.php on line 29
PHP Notice: Undefined index: index in /tmp/t.php on line 29
Look at the generated code in the client browser, you'll find that it looks like this:
var joined = [First Element - Sub2, Second Element etc.....]
note the lack of quotes around your inserted strings. You've created Javascript syntax errors, which kills the entire <script> block those variables are embedded within.
As Rob W mentions above, you have to use json_encode() to produce VALID javascript out of your arbitrary text.
As a general rule, if you've got PHP generating anything javascript, and especially when filling in variables like that, use json_encode() - it'll keep these kinds of headaches away.
PHP runs server side and will output its content in to the webpage, before its then rendered in your browser and the JavaScript is run. (meaning when php is running, it has no idea what "index" is because as far as its concerned its never been defined.
I expect what you want to do is move your PHP in to javascript so you can then access it however you like in the page. In your JavaScript just add somthing along the lines of this:
var my_array_in_js = <?php echo json_encode($phparray); ?>;
Which will result in PHP printing its array as json, which can then be read by javascript however you want. Then to read a specific index just use
alert(my_array_in_js[index]);