Home forums Using CanvasJS Chart via JSON Reply To: Chart via JSON

#9129

Anjali
Participant

[Update]

Now we have a Tutorial on Creating Charts from JSON Data in our documentation.

Hello,

You need to create a HTML page that does AJAX request and fetch the data. After getting the data, it will render a Chart. Please refer the below mentioned code :

<html>
<head>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.js"></script>
    <script type="text/javascript" src="CanvasJS.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {

            var dataPoints = [];

            var chart = new CanvasJS.Chart("chartContainer",
            {
                    title: {
                        text: "Basic Column Chart"
                    },
                    data: [
                    {
                        dataPoints: []
                    }]
            });

            // Ajax request for getting JSON data
            //Replace data.php with your JSON API's url

            $.getJSON("data.php", function (data) {

                for (var i = 0; i < data.length; i++) {

                    dataPoints.push({ label: data[i].source, y: data[i].sourcecount });
                }

                chart.options.data[0].dataPoints = dataPoints;
                chart.render();
            });
        });
    </script>
</head>
<body>
    <div id="chartContainer" style="width: 50%; height: 300px;"></div>
</body>
</html>