fractal5 fractal5 - 16 days ago 7
Javascript Question

Highstock chart - JSON input not working

I am trying to create a chart with Highstock from Highcharts, but can't figure out how to supply the correct JSON data from the PHP file.

This is my HTML file. The original URL used for fetching the data in

getJSON
is
http://www.highcharts.com/samples/data/jsonp.php?filename=' + name.toLowerCase() + '-c.json&callback=?


Three different calls are being made. For example, one is:
http://www.highcharts.com/samples/data/jsonp.php?filename=goog-c.json&callback=?

<html><head>

<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

</head><body>

<div id="container" style="height: 400px; min-width: 310px"></div>

<script>
$(function () {
var seriesOptions = [],
seriesCounter = 0,
names = ['MSFT', 'AAPL', 'GOOG'];

/**
* Create the chart when all data is loaded
* @returns {undefined}
*/
function createChart() {

Highcharts.stockChart('container', {

rangeSelector: {
selected: 4
},

yAxis: {
labels: {
formatter: function () {
return (this.value > 0 ? ' + ' : '') + this.value + '%';
}
},
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},

plotOptions: {
series: {
compare: 'percent',
showInNavigator: true
}
},

tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2,
split: true
},

series: seriesOptions
});
}

$.each(names, function (i, name) {

console.log('name: '+name);

$.getJSON('http://localhost/projects/AGF/testobject.php', function (data) {

console.log(data);

seriesOptions[i] = {
name: name,
data: data
};

// 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 += 1;



if (seriesCounter === names.length) {
createChart();
}
});
});
});
</script>

</body></html>


I simply copied the content from that the PHP file is returning and echoed it from my own PHP file
testobject.php


testobject.php:

<?php
echo "?([
[1258934400000,290.88],
[1259020800000,291.25])";
?>


I shortened the JSON to 2 objects and removed the comments. The first
?
is required by the Highstock, which is added as a callback parameter in the original URL. The first number in each object is the integer value of the date.

Eventually I will be the querying the data from a database and outputting it in this format.

My question is why isn't this working, if the responses are essentially the same?

Thanks.

Answer

That question mark is not required by highstock neither are the () so your JSON is invalid. That markup is for JSONP because the highchart is requesting data from a different domain.

Comments