4

I am using google apis to create a simplechart

    [AllowAnonymous]
    public JsonResult PieChart()
    {
      return Json("[[\"State\",\"Total\"],[\"GA\",50], [\"AL\",30]]",JsonRequestBehavior.AllowGet);
    }

I am calling this method via ajax from my View. Below is my View

@{
    ViewBag.Title = "Visuals";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Visuals</h2>
<div id="piechart_3d" style="width: 900px; height: 500px;"></div>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">

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

          var jsonData = $.ajax({
                type: 'GET',
                url: '@Url.Action("PieChart","Home")',
                dataType: "json",
                async: false
           }).responseText;

        var data = google.visualization.arrayToDataTable(jsonData, false);
        var options = {
          title: 'My Daily Activities',
          is3D: true,
        };

        var chart = new google.visualization.PieChart($('#piechart_3d')[0]);
        chart.draw(data, options);
      }

</script>

However I am getting a javascript error on this line saying not an array

var data = google.visualization.arrayToDataTable(jsonData, false);

I have also tried with JSON.Parse but with no success. Thanks for any help.

2
  • Put a breakpoint and look what value the jsonData variable has. Also if it is a string, try to use JSON.parse(jsonData) Commented Mar 20, 2014 at 14:19
  • when I add a watch to JSON.Parse(jsonData) I get "[["State","Total"],["GA",50], ["AL",30]]" and I still get the same error. Commented Mar 20, 2014 at 14:37

2 Answers 2

2

I would try setting the contentType and handling the result in a success handler instead as follows:

      $.ajax({
            type: 'GET',
            url: '@Url.Action("PieChart","Home")',
            dataType: "json",
            contentType: 'application/json; charset=utf-8',
            async: false,
            success: function(result) {
                  jsonData = result;
           }
       });

The data you are returning looks ok to me as I tried this:

http://jsfiddle.net/Qquse/547/

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

Comments

1

Unfortunately hutchonoid's answer didn't completely work for me. I had to change the array code to:

object[][] arr = new object[][] { new object[] { "Trickle", "Count" }, new object[] { "Ga", 50 }, new object[] { "Ga", 50 } };

Comments

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.