Barry P
Barry P

Reputation: 91

How do I retrieve data in jQuery for a flot pie chart?

I am trying to retrieve data for a flot pie chart and want to make sure I am doing it correctly. Any feedback would be appreciated. I will also post my JSON data being returned to verify it has the proper syntax.

   <script src="js/flot/jquery-1.11.2.min.js"></script>
   <script src="js/flot/jquery.flot.js"></script>
   <script src="js/flot/jquery.flot.pie.js"></script>
   <style type="text/css">
   #placeholder { width: 450px; height: 450px; }
   </style>    
  <script type="text/javascript">
       $.ajax({
        url:'../cgi-bin/bpo_piechart.cgi',
        contentType: "application/json; charset=utf-8",
        type: "POST",
        dataType: 'json',
        success: function (data) {
            //alert("should be shown");
            $.plot($("#placeholder"), data, {
                series: {
                    pie: {
                        show: true
                    }
                },
                legend: {
                    labelBoxBorderColor: "none"
                }
            });
        },
        failure: function (response) {
            alert(response.d);
        }

    });
 </script>

And my JSON data being churned out appears like the following: Can someone tell me if this is a problem? I think it's correct, but I might have to parse the quotes inside of the jQuery javascript block later.

[
   {
      "acctlocv":"CHE3",
      "percval":"3774"
   },
   {
      "acctlocv":"CMI-  CRL2",
      "percval":"5"
   },
   {
      "acctlocv":"CMI1",
      "percval":"4106"
   },
   {
      "acctlocv":"CMI2",
      "percval":"10259"
   },
   {
      "acctlocv":"CUST",
      "percval":"75"
   },
   {
      "acctlocv":"HELOCR",
      "percval":"6"
   },
   {
      "acctlocv":"Network",
      "percval":"8675"
   }
]

Upvotes: 2

Views: 1314

Answers (1)

Barbara Laird
Barbara Laird

Reputation: 12717

Yep, it's your JSON. You need "label" and "data" instead of "acctlocv" and "percval".

         [
               {
                  "label":"CHE3",
                  "data":3774
               },
               {
                  "label":"CMI-  CRL2",
                  "data":5
               },
               {
                  "label":"CMI1",
                  "data":4106
               },
               {
                  "label":"CMI2",
                  "data":10259
               },
               {
                  "label":"CUST",
                  "data":75
               },
               {
                  "label":"HELOCR",
                  "data":6
               },
               {
                  "label":"Network",
                  "data":8675
               }
            ]

http://jsfiddle.net/xyktLseo/1/

Edit - Raidri's comment is correct, 'data' can be strings and flot will convert. http://jsfiddle.net/xyktLseo/2/

Upvotes: 1

Related Questions