In this article I will explain with an example, how to create Charts using
JSON,
JavaScript &
jQuery in HTML.
The HTML5 Canvas charts have been implemented using
Chart.js library to which
JSON object is supplied as source of data.
ChartJS plugin
Please refer the following link for documentation for the
jQuery Chart plugin.
HTML Markup
The HTML Markup consists of following element:
canvas – For displaying chart.
<canvas id="dvChart"></canvas>
Populating Chart using JSON data
Inside the HTML Markup, the following script files are inherited.
1. jquery.min.js
2. chart.umd.min.js
Inside the
jQuery document ready event handler, an Array is created which will hold the
JSON objects and the multiple
JSON objects are added to the Array.
Each
JSON object comprises of:
1. Name - This value will be displayed in legend.
2. Popularity - This value will be used to populate the Pie chart.
3. Color – This value will be used to add color to the Pie chart.
Then, the
PopulateChart JavaScript function is called which accepts two parameters:
1. JSON object – The JSON string received from Server-Side (Code-Behind) is converted to JSON object.
2. Chart type – The type of chart.
PopulateChart JavaScript function
Inside this function, the canvas element is referenced and passed as parameter to the Chart object of the Chart.js library.
Then, type and data is assigned and the data is defined with labels and datasets.
Inside the labels the
Name property of the
JSON object is set.
For datasets, the following properties i.e data, backgroundColor, borderColor, borderWidth are set.
Finally, the legends are defined and the Chart is populated.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js"></script>
<script type="text/javascript">
$(function () {
// Array of Fruits
var fruits = new Array();
var fruit = {};
fruit.Name = "Mango";
fruit.Popularity = 20;
fruit.Color = "#FEBD01";
fruits.push(fruit);
fruit = {};
fruit.Name = "Orange";
fruit.Popularity = 40;
fruit.Color = "#FF8C00";
fruits.push(fruit);
fruit = {};
fruit.Name = "Peach";
fruit.Popularity = 55;
fruit.Color = "#FFCBA6";
fruits.push(fruit);
PopulateChart(fruits, 'pie');
});
function PopulateChart(chartData, chartType) {
var dvChart = $('#dvChart');
var chart = new Chart(dvChart, {
type: chartType,
data: {
labels: chartData.map(fruit => fruit.Name),
datasets: [{
data: chartData.map(fruit => fruit.Popularity),
backgroundColor: chartData.map(fruit => fruit.Color),
borderColor: ['#FFF'],
borderWidth: 1
}]
},
options: {
plugins: {
legend: {
labels: {
boxWidth: 10, // Width of legend box
boxHeight: 10 // Height of legend box
},
display: true, // Show hide legends
position: 'right', //'left', 'right', 'top', 'bottom'
align: 'center', // 'start', 'center', 'end'
reverse: false // Reverse order
}
}
}
});
};
</script>
Screenshot
Demo
Downloads