1

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

jsonData

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');
data.addRows(jsonData);

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

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

Thanks

0

1 Answer 1

2

You must restructure your jsonData before creating your chart instance. If you have 2 columns, you 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');
data.addRows(chartData);

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. https://jsfiddle.net/wp0kLmj5/

Sign up to request clarification or add additional context in comments.

8 Comments

Hello @niboc thanks for reply but its not working, first error is missing ] in loop and other is this output of console.log(chartData); [["0", "["], ["1", "{"], ["2", """] ....
Can you paste your jsonData as it was returned?
[{"India":149,"United States":1375,"Taiwan":22,"Pakistan":21,"Slovak Republic":7,"Cambodia":1,"Macau":1,"Estonia":1,"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}]
Hello @niboc if you see in above data, first value is country name and second is value.
Code Edited. Try now please.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.