Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading a Google Chart asynchronously?

I have the following code to load a Google Chart:

function drawChart1() {
        var jsonData1 = $.ajax({
        url: "library/json_netsales.php",
        dataType:"json",
        async: false
    }).responseText;

    // Create our data table out of JSON data loaded from server.
    var data1 = new google.visualization.DataTable(jsonData1);
    var formatter = new google.visualization.NumberFormat(
        {negativeParens: true, pattern: '$###,###'});
    formatter.format(data1, 1);

    // Instantiate and draw our chart, passing in some options.
    var chart1 = new google.visualization.AreaChart(document.getElementById('chart_netsales'));
    chart1.draw(data1, {width: 300, height: '100%', hAxis: { textPosition: 'none', baselineColor: '#fff' }, vAxis: { textPosition: 'none', baselineColor: '#fff', gridlines: {count: 0}, minValue: 0}, chartArea:{width:"100%",height:"80%"}, legend: {position: 'none' }, backgroundColor: '#232323', colors: ['#fff']});
}

Now the problem is the async flag has been turned off meaning I get page lock-ups. I want to load this asynchronously but I've failed in my attempts to get this to work.

I thought that moving everything past .responseText into a success handler and removing the async:false line would get this working, but I was wrong.

Any ideas of how to get a Google Chart to load asynchronously?

like image 811
Donavon Yelton Avatar asked Oct 02 '13 19:10

Donavon Yelton


1 Answers

This should work:

function drawChart1() {
    $.ajax({
        url: "library/json_netsales.php",
        dataType: "json",
        success: function (json) {
            // Create our data table out of JSON data loaded from server.
            var data1 = new google.visualization.DataTable(json);
            var formatter = new google.visualization.NumberFormat({
                negativeParens: true,
                pattern: '$###,###'
            });
            formatter.format(data1, 1);

            // Instantiate and draw our chart, passing in some options.
            var chart1 = new google.visualization.AreaChart(document.getElementById('chart_netsales'));
            chart1.draw(data1, {
                width: 300,
                height: '100%',
                hAxis: {
                    textPosition: 'none',
                    baselineColor: '#fff'
                },
                vAxis: {
                    textPosition: 'none',
                    baselineColor: '#fff',
                    gridlines: {count: 0},
                    minValue: 0
                },
                chartArea: {
                    width:"100%",
                    height:"80%"
                },
                legend: {position: 'none'},
                backgroundColor: '#232323',
                colors: ['#fff']
            });
        }
    });
}
like image 168
asgallant Avatar answered Sep 28 '22 07:09

asgallant