JavaScript Charts from JSON Data API and AJAX

Here is a turtorial on creating Charts using JSON Data from an external source. Generally it’s a good idea to fetch data via ajax rather than embedding in the web page. JSON data is easy to parse and generate the chart accordingly.

Here are the steps for creating Charts using JSON Data.

We will be using following JSON format (2 dimensional array) in this example:

 [[1,12],[2,7],[3,6],[4,6],[5,9],[6,13],[7,12],[8,15],[9,14],[10,18]]

As a first step we need get data by making an AJAX call (we use jQuery) and then parse the same to convert the data into CanvasJS DataPoints – like {x: 5, y: 6}. Please refer to Working with Data for more information. Then we will initialize a chart and pass the dataPoints.

var dataPoints = [];
var chart = new CanvasJS.Chart("chartContainer",{
    title:{
        text:"Rendering Chart with dataPoints from External JSON"
    },
    data: [{
        type: "line",
        dataPoints : dataPoints,
    }]
});
$.getJSON("https://canvasjs.com/services/data/datapoints.php?xstart=1&ystart=10&length=100&type=json", function(data) {  
    $.each(data, function(key, value){
        dataPoints.push({x: value[0], y: parseInt(value[1])});
    });
    chart.render();
});

Finalising

To summarize, in order to create a charts using JSON Data from external source we need to first fetch data using AJAX, create CanvasJS Data Points and then push the same into an array for plotting and call chart.render().

Below is the compilation of final code.

Try it Yourself by Editing the Code below.


If you have any questions, please feel free to ask in our forums.Ask Question