Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use google chart using dynamic data from json

iam using mvc, i want to connect my data to google pie chart. so i used json to get list of names and their count using the following code

public JsonResult list()
        {
     var result= list.GroupBy(i => i.Name).Select(i => new { word = i.Key, count = i.Count() 
return Json(result.ToList(), JsonRequestBehavior.AllowGet);
}

Using the google chart API

 google.load("visualization", "1", { packages: ["corechart"] });
    google.setOnLoadCallback(drawChart);
    function drawChart() {

        var jsonData = $.ajax({
            url: "list",
            dataType: "json",
            async: false
        }).responseText;
        var data = google.visualization.DataTable(jsonData);

        var options = {
            title: 'Certificate details',
            is3D: true,
        };    
        var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
        chart.draw(data, options);
    }

i want to know how to get list of key value pairs of my data into pie chart. i have googled for long time, everybody is giving code example with php. Thankyou.

like image 254
coder Avatar asked Mar 27 '14 06:03

coder


1 Answers

You can parse that data client-side like this:

function drawChart () {
    $.ajax({
        url: "list",
        dataType: "json",
        success: function (jsonData) {
            var data = new google.visualization.DataTable();
            // assumes "word" is a string and "count" is a number
            data.addColumn('string', 'word');
            data.addColumn('number', 'count');

            for (var i = 0; i < jsonData.length; i++) {
                data.addRow([jsonData[i].word, jsonData[i].count]);
            }

            var options = {
                title: 'Certificate details',
                is3D: true
            };
            var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
            chart.draw(data, options);
        }
    });
}
like image 81
asgallant Avatar answered Sep 21 '22 22:09

asgallant