0
votes

Is there a special way of creating a google chart via an Ajax call, which is different from the static method?

The HTML i am producing is correct because it will load from a normal HTML file, but when im calling the Ajax, the data in the graph is not showing.

I am using google.setOnLoadCallback() and google.load('visualization', '1', {packages: ['table']})

1

1 Answers

0
votes

You need to get data from ajax call and then put it in to your visualization function. Here is my code:

google.load('visualization', '1', { packages: ['corechart'] });
google.setOnLoadCallback(OnLoad);   

var url = '/Charting/GetData';
function OnLoad() {
    $.ajax({
        url: url,
        dataType: 'json',          
        success: function (response) {
            drawVisualization(response);
        }
    });
};

function drawVisualization(response) {
   var chart = new google.visualization.ColumnChart(
       document.getElementById('visualization'));

   var data = new google.visualization.DataTable(response);   
   chart.draw(data);
};

Also i recommend you to use this class to generate correct JSON response:

public class ChartHelper
{
    public ColInfo[] cols { get; set; }
    public DataPointSet[] rows { get; set; }    
}

public class ColInfo
{
    public string id { get; set; }
    public string label { get; set; }
    public string type { get; set; }
}

public class DataPointSet
{
    public DataPoint[] c { get; set; }
}

public class DataPoint
{
    public object v { get; set; } // value
    public string f { get; set; } // format
}

Then you can use it like this:

[ActionName("data")]
public JsonResult Data()
{
   Random r = new Random();
   var graph = new ChartHelper
   {
       cols = new ColInfo[] {
           new ColInfo { id = "A", label = "Name", type = "string" },
           new ColInfo { id = "B", label = "Value", type = "number" },
       },
       rows = new DataPointSet[] {
           new DataPointSet { 
               c = new DataPoint[] 
               {
                   new DataPoint { v = "Name" },
                   new DataPoint { v = r.NextDouble()},
               }},
           new DataPointSet {
               c = new DataPoint[]
               {
                   new DataPoint { v = "Name2" },
                   new DataPoint { v = r.NextDouble()},
               }},
           new DataPointSet {
               c = new DataPoint[]
               {
                   new DataPoint { v = "Name3" },
                   new DataPoint { v = r.NextDouble()},
               }} 
            }
        };

        return Json(graph, JsonRequestBehavior.AllowGet);
    }