Flot Pie Chart with PHP

2019-08-20 17:01发布

问题:

I tried to add load a Pie Chart dynamically using Flot Chart and PHP/MySQL.

This is my javascript code

 <script id="source" language="javascript" type="text/javascript">


  function fetchData() {
   $.ajax({
      url:      "test.php",
      method:   "GET",
      dataType: "json",
      success:  function(series) {
         var data = [  series ];
         $.plot($("#graph1"), data, {
            pie: { 
                show: true,
                showLabel: true
            },
            legend: {
                show: false 
            }
        });
      }
   });

   setTimeout(fetchData, 1000);
}


$(function () {
    $("#btn").click(function(){
    fetchData();                       
  });   

});

This is my PHP Code

<?php 
    include("db.php");
    $return_arr = array();
    $sql = mysql_query("SELECT item, COUNT(target) FROM counter WHERE type='video' and date BETWEEN '2011-02-21' and '2011-02-26' GROUP BY target ORDER BY id ASC");
    while($obj = mysql_fetch_object($sql)){
        $return_arr[] = $obj;   
    }
    echo json_encode($return_arr);
?>

This is my button

<input type="submit" value="click" id="btn"/>

This is the array that I get when I click the button

[{"item":"Final 2010","COUNT(target)":"2"},{"item":"Semi Final 2009","COUNT(target)":"3"}]

When I click the button, it gives me this error:

An invalid or illegal string was specified" code: "12
[Break On This Error] false 

and Even the pie chart is not loading. Can anybody tell me where did I made the wrong.

When I check in firebug, the array is showing like this

[{"item":"Final 2010","COUNT(target)":"2"},{"item":"Semi Final 2009","COUNT(target)":"3"}]

But when I print it, it shows as [Object object][Object object], I think that would be the problem, anyone know how to fix it

Thanks

回答1:

I think you need to eval that data (series)

var data    = eval("(" + series + ")");

That should do it, I think

EDIT

Added a simple replication on jsfiddle : http://jsfiddle.net/TVAWL/1/