tuze tuze - 9 days ago 6
Javascript Question

Google Charts fetching from Json

I'm trying to create charts using Google Charts Api. My data is stored as a json file as shown.

{
"1":[{"a":0,"d":0}],
"2":[{"a":0,"d":0}],
"3":[{"a":6,"d":62.92}],
"4":[{"a":1.57,"d":75.32}],
"5":[{"a":1.67,"d":66.45}],
"6":[{"a":1.25,"d":76}],
"7":[{"a":1.36,"d":75.08}],
"8":[{"a":1.59,"d":69.27}],
...
}


I'm fetching json file, pushing the objects to a javascript array. It works with no problem. I added these lines to understand what's happening. However Google Api doesn't accept my values and shows only

dots.push([5, 50]);
dots.push([7,60]);


Here's my code

function drawDots()
{
var data = new google.visualization.DataTable();
data.addColumn('number', 'a');
data.addColumn('number', 'd');

dots = new Array;
dots.push([5, 50]);
dots.push([7,60]);

$.getJSON("/graph/graph.json", function(json)
{
$.each(json, function(id, num)
{
$.each(num, function(i, e)
{
dots.push([e.a, e.d]);
});
});

});

data.addRows(dots);

var options = {
title: '',
hAxis: {title: 'Data 1', minValue: 0, maxValue: 100},
vAxis: {title: 'Data 2', minValue: 0, maxValue: 100},
legend: 'none'
};

var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));

chart.draw(data, options);
}


Data type of the values are number, I also tried eval() to. In console, values are seems in array. Can't understand what's wrong.

Here's the console log of dots and data with a screen shot.
enter image description here

Answer

The problem is with the asynchronous getJSON call. The getJSON call happens but while it's still retrieving the contents of graph.json, the rest of the code executes. This means that the getJSON callback runs after the chart has been drawn.

Solution: Move the chart drawing code into the getJSON callback:

function drawDots()
{  
    var data = new google.visualization.DataTable();
    data.addColumn('number', 'a');
    data.addColumn('number', 'd');

    dots = new Array;
    dots.push([5, 50]);
    dots.push([7,60]);

    $.getJSON("/graph/graph.json", function(json)
    {
        $.each(json, function(id, num)
        {
            $.each(num, function(i, e)
            {           
                dots.push([e.a, e.d]);
            });
        }); 

        data.addRows(dots);

        var options = {
            title: '',
            hAxis: {title: 'Data 1', minValue: 0, maxValue: 100},
            vAxis: {title: 'Data 2', minValue: 0, maxValue: 100},
            legend: 'none'
        };

        var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));

        chart.draw(data, options);
    }); 
}