IsharaRA
IsharaRA

Reputation: 45

How to pass values to a chart (chart.js / morris.js)

With PHP I am trying to get data from MySQ database and display it on a area chart(revenue). Following is my PHP code:

$q = "SELECT `sales`, `quantity` FROM `sap` WHERE `d_channel`='$disC' AND `sales_org`='$plant' AND `date` BETWEEN '$fd' AND '$td'";
$result = mysqli_query($dbc,$q);

$array = array();
while($row = mysqli_fetch_assoc($result))
{
    array_push(
        $array,
        array(
            'x' => $row['sales'],
            'y' => $row['quantity'],
        )
    );                
}

echo json_encode($array);

And the output is:

[
  {"x":"101151.7","y":"10"},
  {"x":"14660.53","y":"20"},
  {"x":"505344","y":"50"}
]

I have passed the array to chart as follows:

<div id="morris-line-chart"></div>

<script>
    Morris.Line({
        // ID of the element in which to draw the chart.
        element: 'morris-line-chart',

        // Chart data records -- each entry in this array corresponds to a point
        // on the chart.
        data: <?php echo json_encode($array);?>,

        // The name of the data record attribute that contains x-values.
        xkey: 'cron_time',

        // A list of names of data record attributes that contain y-values.
        ykeys: ['images_processed'],

        // Labels for the ykeys -- will be displayed when you hover over the
        // chart.
        labels: ['Images Processed'],

        lineColors: ['#0b62a4'],
        xLabels: 'hour',

        // Disables line smoothing
        smooth: true,
        resize: true
    });
</script>

But it gives an error "Uncaught TypeError: Cannot read property 'match' of undefined" FYI I have used following links

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>

Please help me to solve my problem.

Upvotes: 3

Views: 1047

Answers (1)

krlzlx
krlzlx

Reputation: 5822

Try to change your xkey and ykeys. Because your actual cron_time and images_processed doesn't exist in your json data.

xkey: 'x', // 'cron_time',
ykeys: ['y'], //['images_processed'],

Or change the keys in your php and keep the actual Morris config:

array
(
    'cron_time' => $row['sales'],
    'images_processed' => $row['quantity'],
)

You should also convert your quantity to int or float:

(int)$row['quantity']
(float)$row['quantity']

Upvotes: 1

Related Questions