Enjayy
Enjayy

Reputation: 1074

Google Charts and Ajax Response's

I have been working on this for quite some time. And I cannot seem to figure out why I cannot populate my charts. I am using the google charts api. When I pass the data to

new google.visualization.DataTable(getData(playWithData))

it returns "Table Has No Columns".

This is my current ajax call to my controller

function getData(callback){
    $.ajax({
      type: "GET",
      url: '/lead_sources',
      dataType: 'json'
    }).done(function(data){
      callback(data);
    })
  }

  function playWithData(data){
    console.log(data);
  }

  var data = new google.visualization.DataTable(getData(playWithData))

Inside the console enter image description here

Currently I am using dummy data from my controller to get the ajax call to work properly. Formatting similar to the DOCUMENTATION https://developers.google.com/chart/interactive/docs/reference#dataparam

{
      cols: [{label: 'Week', type: 'string'},
             {label: 'Facebook', type: 'number'},
             {label: 'Twitter', type: 'number'},
             {label: 'Instagram', type: 'number'}
      ],
      rows: [{c:[{v: 'Week 1'},
                 {v: 5,  f: 'Five'},
                 {v: 12, f: 'Twelve'},
                 {v: 4, f: 'Four'}
            ]}
      ]
    }

Im not sure if I am missing something or I am doing something completely wrong. Any help would be great!

Upvotes: 1

Views: 58

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

Your issue is a combination of async logic executing in a manner you're not anticipating, and the fact that neither of your functions returns any data.

You need to create the DataTable in the callback function itself, once the data has been retrieved. Try this:

function getData(){
    $.ajax({
        type: "GET",
        url: '/lead_sources',
        dataType: 'json'
    }).done(function(data){
        var dataTable = new google.visualization.DataTable(data);
        // amend settings of dataTable here, as needed

        var table = new google.visualization.Table(document.getElementById('table_div'));
        table.draw(dataTable, { showRowNumber: true });
    })
}

getData(); // call when required  

Upvotes: 1

Related Questions