Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

load google charts through an ajax call

I'm trying to call the google chart after clicking on a link. This is what my function looks like:

function getGraphData(id) {

    var ajax_url = '<?=URL?>ajaxlibrary/get-graph-data';

    $.ajax({
        type: 'POST',
        url: ajax_url,
        dataType: 'html',
        data: ({
            id : id
      }),
        cache: false,
        success: function(data) {
            $('a').removeClass("selected");
            $('#link_'+id).addClass("selected");
            alert(data);

        },
    });
}

So what I'm trying to achieve here is to load a different graph for a different like, so lets say I have politics charts, sports charts etc. I don't know where to put the Google API code though, because it seems it's just not working...

EDIT: I edited the function like this:

  $.ajax({
         type: "POST",
         dataType: "html",
         data: {id: id},
         url: '<?=URL?>' + 'ajaxlibrary/get-charts',
         success: function(datas) {
            console.log(datas);
            var data = google.visualization.arrayToDataTable([
                    datas
            ]);

            var options = {
                title: 'My Daily Activities'
            };

            var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
            chart.draw(data, options);
         }
    }); 

but i'm having issues with sending this data stream from my ajax php file:

echo '[\'Task\', \'Hours per Day\'],
            [\'Work\',     10],
            [\'shit\',     50],
            [\'loop\',     25],
            [\'poop\',     15]';

the response is not a valid 2D array. If I put the values in the javascript file manually, it works, so the issue is somewhere in the response.

like image 398
InsaneSVK Avatar asked May 21 '13 10:05

InsaneSVK


1 Answers

You can load the Google Charts with Ajax call using below code.

$.ajax({
  url: 'https://www.google.com/jsapi?callback',
  cache: true,
  dataType: 'script',
  success: function(){
    google.load('visualization', '1', {packages:['corechart'], 'callback' : function()
      {

            $.ajax({
                 type: "POST",
                 dataType: "json",
                 data: {id: YOURIDHERE},
                 url: '<?=URL?>' + 'ajaxlibrary/get-charts',
                 success: function(jsondata) {
                    var data = google.visualization.arrayToDataTable(jsondata);

                    var options = {title: 'My Daily Activities'};

                    var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
                    chart.draw(data, options);
                 }
            });    
        ]);

      }
    });
    return true;
  }
});

you can load any other chart types instead of just the corechart using Google API.

like image 58
Nagarjun Avatar answered Oct 24 '22 20:10

Nagarjun