Simple data visualization with HTML5 form and Chart.js

In recent, data visualization becomes more important because it presents a better conversation between customer and business. The company can even through the business intelligence tools to transfer their data to information to drive values. This article will show you how to use HTML5 Chart.js to deliver a simple chart for data visualization.

View Demo

Usage:

1. Create a HTML5 form.
2. Serize all the data from the form.
3. Convert it to JSON format.
4. Using ajax to receive data.
5. Display you data via Chart.js

At the beginning we have to do is create a simple HTML form.

<form id="myForm">
            <div class="form-group">
                <label for="red" >ChartColors.Red</label>
                <input type="number" step="any" class="form-control" id="red" name="red"  >
            </div>
            <div class="form-group">
                <label for="purple" >ChartColors.Purple</label>
                <input type="number" step="any" class="form-control" id="purple" name="purple"  >
            </div>
            <div class="form-group">
                <label for="yellow" >ChartColors.Yellow</label>
                <input type="number" step="any" class="form-control" id="yellow" name="yellow"   >
            </div>
            <div class="form-group">
                <label for="green" >ChartColors.Green</label>
                <input type="number"step="any" class="form-control" id="green" name="green" >
            </div>
             <div class="form-group">
                <label for="blue" >ChartColors.Blue</label>
                <input type="number" step="any" class="form-control" id="blue" name="blue"  >
            </div>
</form> 
<canvas id="barchart"></canvas>
<canvas id="piechart"></canvas>

The label should name same as the input id, so it could focus on that form when user click on the text. We also make two canvas tags for displaying the charts as bar chart and pie chart.

Next, create an external JavaScript file and write the below code.

$("input").keyup(function(){

// request form array values
$.fn.extend = function(){
               
var formData = {}; 
var formArray = $('#myForm').serializeArray();  
  for(var i = 0 ; i < formArray.length; i++){
    formData[formArray[i].name] = formArray[i].value;
  }
  return formData;

};
Notice you have to install jQuery library at first.

In here, we create a keyup function when user start typing in their form. Then, seize all the data from our custom form id and make it each value as an Array. Finally, we return the data value so it can be used in the future.

// convert to JSON data
var myJSON = JSON.stringify($('form').extend())

// Retrieve the Pie and Bar chart JSON data via Ajax HTTP GET requests.
$.ajax({
  url: 'index.html',
  type: 'GET',
  data: myJSON,
  success: function () {
    //Do stuff with the JSON data
    $("#div2").html("<h4><br>"+myJSON.split(",").join(", <br><br>")+"</h4>")
  },
  error: function () {
    $("#div2").html("<h4>Ajax Request Failed. <br><br> Please make sure you are using webserver.</h4>")
  }
});

The next step is to convert these value to JSON format so it can be accepted by ajax request. You can actually skip this if you do not want your data transfer to back-end server.

Now, we have to apply Chart.js into our website. Parse the json value as object and make variables to the color.

// parse json value as obj
obj = JSON.parse(myJSON);

// console.log(obj);

//pie
var ctx = $('#piechart')[0].getContext('2d');
//bar
var ctx2 = $('#barchart')[0].getContext('2d');

//both
var ChartColor = [
    window.chartColors.red,
    window.chartColors.purple,
    window.chartColors.yellow,
    window.chartColors.green,
    window.chartColors.blue
];

var ChartLabels = ["Red", "Purple", "Yellow", "Green", "Blue"];

var ChartData = [
     window.obj.red,
     window.obj.purple,
     window.obj.yellow,
     window.obj.green,
     window.obj.blue
];

        //fix the bug
        if(window.myPie != undefined){
            window.myPie.destroy();
        }


        //pie
        window.myPie = new Chart(ctx, {
                type: 'pie',
                data: {
                    labels: ChartLabels,
                    datasets: [{
                        data: ChartData,
                        backgroundColor: ChartColor,
                    }]
                },
                options: {
                    title: {
                        display: true,
                        text: 'Pie Chart'
                    }
                }
        });

        

        //fix the bug
        if(window.myBar != undefined){
            window.myBar.destroy();
        }

        //bar
        window.myBar = new Chart(ctx2, {
                type: 'bar',
                data: {
                    labels: ChartLabels,
                datasets: [{
                    data: ChartData,
                    backgroundColor: ChartColor,
                }],
                },
                options: {
                    legend: {
                        display: false
                    },
                    title: {
                        display: true,
                        text: 'Bar Chart'
                    }
                }

            });

That’s it! You final html and javascript files should look like below.

index.html

<!doctype html>
<html>

<head>
<title>My Chart</title>
 

<!-- bootstrap css-->
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/bootstrap-theme.min.css" >
<!-- custom css -->
<link rel="stylesheet" href="css/style.css" >

<!-- jquery -->
<script src="js/jquery-3.1.1.min.js"></script>

<!-- bootstrap js-->
<script src="js/bootstrap.min.js" ></script>

<!-- chart.js js -->
<script src="js/Chart.bundle.min.js"></script>
<script src="js/Chart.min.js"></script>
<script src="js/utils.js"></script>

</head>
<body>
<div class="column">
<h4 class="text-center">Please Type the Number</h4>
    <div class="row">
        <div class="col-xs-4">
<!-- You form start here... -->
            <form id="myForm">
            <div class="form-group">
                <label for="red" >ChartColors.Red</label>
                <input type="number" step="any" class="form-control" id="red" name="red"  >
            </div>
            <div class="form-group">
                <label for="purple" >ChartColors.Purple</label>
                <input type="number" step="any" class="form-control" id="purple" name="purple"  >
            </div>
            <div class="form-group">
                <label for="yellow" >ChartColors.Yellow</label>
                <input type="number" step="any" class="form-control" id="yellow" name="yellow"   >
            </div>
            <div class="form-group">
                <label for="green" >ChartColors.Green</label>
                <input type="number"step="any" class="form-control" id="green" name="green" >
            </div>
             <div class="form-group">
                <label for="blue" >ChartColors.Blue</label>
                <input type="number" step="any" class="form-control" id="blue" name="blue"  >
            </div>
            </form>
</div>
<!-- display charts with HTML5 canvas -->
        <div class="col-xs-8">
            <div class="col-xs-6">
                <canvas id="barchart"></canvas>
                <div id="div2"></div>
            </div>

            <div class="col-xs-6">
                <canvas id="piechart"></canvas>
            </div> 
            
        </div>
        </div>
</div>

<!-- chartjs start here -->
<script src="js/mychart.js" ></script>

mychart.js

// typing function...
$("input").keyup(function(){

// request form array values
$.fn.extend = function(){
               
var formData = {}; 
var formArray = $('#myForm').serializeArray();  
  for(var i = 0 ; i < formArray.length; i++){
    formData[formArray[i].name] = formArray[i].value;
  }
  return formData;

};  

// convert to JSON data
var myJSON = JSON.stringify($('form').extend())

// Retrieve the Pie and Bar chart JSON data via Ajax HTTP GET requests.
$.ajax({
  url: 'index.html',
  type: 'GET',
  data: myJSON,
  success: function () {
    //Do stuff with the JSON data
    $("#div2").html("<h4><br>"+myJSON.split(",").join(", <br><br>")+"</h4>")
  },
  error: function () {
    $("#div2").html("<h4>Ajax Request Failed. <br><br> Please make sure you are using webserver.</h4>")
  }
});


// parse json value as obj
obj = JSON.parse(myJSON);

// console.log(obj);

//pie
var ctx = $('#piechart')[0].getContext('2d');
//bar
var ctx2 = $('#barchart')[0].getContext('2d');

//both
var ChartColor = [
    window.chartColors.red,
    window.chartColors.purple,
    window.chartColors.yellow,
    window.chartColors.green,
    window.chartColors.blue
];

var ChartLabels = ["Red", "Purple", "Yellow", "Green", "Blue"];

var ChartData = [
     window.obj.red,
     window.obj.purple,
     window.obj.yellow,
     window.obj.green,
     window.obj.blue
];

        //fix the bug
        if(window.myPie != undefined){
            window.myPie.destroy();
        }


        //pie
        window.myPie = new Chart(ctx, {
                type: 'pie',
                data: {
                    labels: ChartLabels,
                    datasets: [{
                        data: ChartData,
                        backgroundColor: ChartColor,
                    }]
                },
                options: {
                    title: {
                        display: true,
                        text: 'Pie Chart'
                    }
                }
        });

        

        //fix the bug
        if(window.myBar != undefined){
            window.myBar.destroy();
        }

        //bar
        window.myBar = new Chart(ctx2, {
                type: 'bar',
                data: {
                    labels: ChartLabels,
                datasets: [{
                    data: ChartData,
                    backgroundColor: ChartColor,
                }],
                },
                options: {
                    legend: {
                        display: false
                    },
                    title: {
                        display: true,
                        text: 'Bar Chart'
                    }
                }

            });


});  // type function end

For more information, please visit the Chart.JS API Documentation to customize.

Thanks!

Reference featured image: http://www.chartjs.org/

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *