Mr.SH Mr.SH - 10 months ago 38
Ajax Question

Google Charts Add data from PHP Ajax

I am trying to generate google charts using PHP and ajax.

my php file is returning values as bellow

["India":149,"United States":1375,"Taiwan":22,"Latvia":1,"New Zealand":2,"Argentina":1,"Namibia":4,"Ghana":4,"Mauritania":1,"Sudan":3,"Kazakhstan":2,"Nigeria":3,"Kenya":2,"FYROM":1,"Nepal":4}]

into vribale


i am trying to add these values in Google Charts with bellow code

var data = new google.visualization.DataTable(jsonData);

its giving error as i assume that there is no Colums define in value. so i change code to bellow

var data = new google.visualization.DataTable();
data.addColumn('string', 'Country');
data.addColumn('number', 'Value');

this is also giving me error that value must be array.

how to fix this, as i can't change result from PHP file.



You must restructure your jsonData before creating your chart instance. If you have 2 columns, yo need to transform json into array of array, in your case it'll look like:

[["India",149],["United States",1375], ....["Nepal":4]]

Try this:

var chartData = [];
for(var i in jsonData[0])
    chartData.push([i, jsonData[0][i]]);//This create ["Key", Value] for each value in jsonData

var data = new google.visualization.DataTable();
data.addColumn('string', 'Country');
data.addColumn('number', 'Value');

Hope this help

EDIT 1: Your jsonData variable is not valid, did you pasted it okay? It might be an associative array? Like { "India" : 123, "Argentina" : 456 } ? My example work with associative array, so it is not tell me.

EDIT 2: You must add [0] to jsonData, because it is an array of an associative array. Try it now.

EDIT 3: Here is the code working.