Kevin Johnson
Kevin Johnson

Reputation: 107

flot piechart from PHP

I am having a very strange issue creating a piechart in Flot with data from PHP.

It seems to be drawing incorrectly, and I can't figure out why.

My PHP code (for testing) is:

echo json_encode(
'[{ label: "Series1",  data: 10},
{ label: "Series2",  data: 3},
{ label: "Series3",  data: 9},
{ label: "Series4",  data: 7},
{ label: "Series5",  data: 8},
{ label: "Series6",  data: 17}]'
);

My JS file is:

$.ajax({
type:'GET',
dataType:"json",
url:'../phpfile.php',
success: function(data) {
    console.log(data);
    $.plot($("#piechart"),data,{
        series: {
            pie: {
                show: true
            }
        }
    });
}
});

The consol log shows:

[{ label: "Series1",  data: 10},
{ label: "Series2",  data: 3},
{ label: "Series3",  data: 9},
{ label: "Series4",  data: 7},
{ label: "Series5",  data: 8},
{ label: "Series6",  data: 17}]

Which I thought was the correct format for flot...

But it graphs like this: piechart

Does anyone have any ideas?

Upvotes: 1

Views: 1928

Answers (1)

MackieeE
MackieeE

Reputation: 11862

I believe your JSON currently is invalid, at the moment, you're trying to parse an JSON String, into a JSON String (If you get what I mean!) Currently, when I echo out from the PHP end with your echo'ed json_encode(), I'm provided with:

"[{ label: \"Series1\", data: 10},\r\n{ label: \"Series2\"]"

Furthermore, I would use PHP Arrays to encode JSON, like below:

<?php 
    $arr = array( 
        array(
            "label" => "Series1",
            "data" => 10
        ),
        array(
            "label" => "Series2",
            "data" => 3
        ),
        array(
            "label" => "Series3",
            "data" => 9
        ),
        array(
            "label" => "Series4",
            "data" => 7
        ),
        array(
            "label" => "Series5",
            "data" => 8
        ),
        array(
            "label" => "Series7",
            "data" => 17
        )
    );

    echo json_encode( $arr );
?>

PHP json_encode() does accept mixed variable types, but it's most popularly used with PHP arrays.

With the above, I'm able to construct the PIE chart successfully:

Finished Chart

Upvotes: 1

Related Questions