pathros pathros - 5 months ago 57
jQuery Question

Error: Not an array in Google charts

I have manage to output the results from the database by outputting the following string:

[['Grupo de edad','Mujeres','Hombres'],['Menos de 40',2,0],['De 40 a 49',7,3],['De 50 a 59',8,5],['De 60 a 69',20,25],['De 70 y más',6,10]]


If i paste exactly this text into the following:

var data = google.visualization.arrayToDataTable([['Grupo de edad','Mujeres','Hombres'],['Menos de 40',2,0],['De 40 a 49',7,3],['De 50 a 59',8,5],['De 60 a 69',20,25],['De 70 y más',6,10]]);


I can visualize correctly the chart.

However, if i get the data by using jQuery .get() function and then i pass the data to google visualization function like the following:

google.load("visualization", "1.1", {packages:["corechart","bar"]});
google.setOnLoadCallback(drawVisualization);

function drawVisualization() {
$.get("{{URL::action('ChartController@investigadoresEdadSexo')}}", function(datos, status){
var data = google.visualization.arrayToDataTable(datos);
var options = {
//many options ...
};

var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
});//End of jQuery .get
}


I get the


Not an Array error


I know that i am passing a string, but why doesn't it work if i have tested that string by typing (copying and pasting) google.visualization.arrayToDataTable() function? Or how do i make that function interpret that string as an array?

How do i fix this?

Answer

Try to convert datos to an array using JSON.parse:

var data = google.visualization.arrayToDataTable(JSON.parse(datos));

UPDATE

Before parsing datos quotes ' should be transformed to ":

datos = datos.replace(/'/g, '"');
var data = google.visualization.arrayToDataTable(JSON.parse(datos));