Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding series to highcharts from JSON

I'm trying to add a series to a highcharts chart from JSON data. The json has dates and y values:

{Date.UTC(2011,8,1): 47, Date.UTC(2011,8,2): 78}

and the javascript function I currently have, which adds the series but the dates don't seem to work, is:

function requestData() {
$.ajax({
    url: 'chartData.php',
    success: function(items) {

        var series = {
            id: 'series',
            name: 'JSON Data',
            data: []
            }

        $.each(items, function(itemNo, item) {
            series.data.push(item);
        });

        chart.addSeries(series);

    },
    cache: false
});
 }

Can anyone help me finish off this query to get the chart working? Thanks in advance for the help!

EDIT: I SOLVED THIS - SEE ANSWER BELOW FOR HOW I DID IT

like image 558
dvanderb Avatar asked Aug 01 '11 23:08

dvanderb


2 Answers

I figured this out. Here's how I did it in case anyone else has the same question:

In my script that generates the JSON data, I did the following:

    header('Content-type: text/json');

    //Placeholder - random data for now
    $x1 = "2011-8-1";
    $y1 = rand(0, 100);

    $x2 = "2011-8-2";
    $y2 = rand(0, 100);

    //Generate this array from database data
    $arr = array($x1 => $y1, $x2 => $y2);

    echo json_encode($arr);

Then, in the ajax script that adds the series to the chart, I did the following:

    function requestData() {
 $.ajax({
    url: 'chartData.php',
    success: function(json) {

        var series = {
            id: 'series',
            name: 'JSON Data',
            data: []
            }

        $.each(json, function(date,value) {
            xval = date.split("-");
            x = Date.UTC(xval[0], xval[1] - 1, xval[2]);
            series.data.push([
                x,
                value
            ]);
        });

        chart.addSeries(series);

    },
    cache: false
});
}
like image 143
dvanderb Avatar answered Nov 17 '22 14:11

dvanderb


In an example from a project I'm working on right now, I evaluate the series data from an array like this. Maybe that is cheating, but I at least got it to work :)

var xAxisCat = new Array();
var hSeries = new Array();
for (var datevote in contestantObject.contestants[cObj].votes)
{
    xAxisCat.push(datevote);
    hSeries.push(contestantObject.contestants[cObj].votes[datevote]);
}
var setSeries = "["+hSeries+"]";

And then, at the series creation I evaluate the created array instead:

series: [{
         name: contestantObject.contestants[cObj].name,
         data: eval(setSeries)
         }]
like image 38
Tomas Tornevall Avatar answered Nov 17 '22 13:11

Tomas Tornevall