lundi 20 avril 2015

Javascript to render charts not working with .getJSON

Correction: /devicedata to /products - that was a typo..

I have built a node-express app which I am using to to plot a graph from the data retrieved from mongo database. I have tried two external libraries Chart.js and Canvas.js. Both work perfectly fine when the data is hard-coded in the javascript. The moment I use $.getJSON to retrieve the data from database it stops working. On the server side code is as below:

app.get('/products', function(req, res) {
    var db = req.db;
    db.collection('products').find().toArray(function (err, items) {
       res.json(items);
    });
});

On the client side code is as below:

<script type="text/javascript">
$(document).ready(function () {

    $.getJSON("/products", function (result) {

        var chart = new CanvasJS.Chart("chartContainer", {
            title:{
                text: "Temperatures recorded this year"
                },
            data: [
                {
                    type: "column",
                    dataPoints: result,
                }
            ]
        });

        chart.render();
    });
});
</script>
<div id="chartContainer" style="height: 300px; width: 100%;">
</div>

Is there an alternative to .getJSON to retrieve data from database (mongo in this case) ? The chart is rendering as a blank canvas

Aucun commentaire:

Enregistrer un commentaire