{"id":459,"date":"2017-05-14T01:32:32","date_gmt":"2017-05-14T07:32:32","guid":{"rendered":"https:\/\/smartlun.com\/?p=459"},"modified":"2020-01-27T08:52:44","modified_gmt":"2020-01-27T15:52:44","slug":"simple-data-visualization-with-html5-form-and-chart-js","status":"publish","type":"post","link":"https:\/\/smartlun.com\/api\/simple-data-visualization-with-html5-form-and-chart-js\/","title":{"rendered":"Simple data visualization with HTML5 form and Chart.js"},"content":{"rendered":"

\"\"<\/p>\n

In recent, data visualization becomes more important\u00a0because it presents a better\u00a0conversation between customer and business. The company\u00a0can 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.<\/p>\nView Demo <\/i><\/a>\n

<\/p>\n

Usage:<\/h4>\n
<\/p>\n

1. Create a HTML5 form.
\n2. Serize all the data from\u00a0the form.
\n3. Convert it to JSON format.
\n4. Using ajax to receive data.
\n5. Display you data via Chart.js<\/p>\n

<\/div>\n

At the beginning we\u00a0have to do is create a simple HTML form.<\/p>\n

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

The label\u00a0should name same as the input\u00a0id, so it could\u00a0focus 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.<\/p>\n

Next, create an external JavaScript file and write the below\u00a0code.<\/p>\n

$(\"input\").keyup(function(){\r\n\r\n\/\/ request form array values\r\n$.fn.extend = function(){\r\n               \r\nvar formData = {}; \r\nvar formArray = $('#myForm').serializeArray();  \r\n  for(var i = 0 ; i < formArray.length; i++){\r\n    formData[formArray[i].name] = formArray[i].value;\r\n  }\r\n  return formData;\r\n\r\n};<\/pre>\n
Notice you have to\u00a0install jQuery library<\/a>\u00a0at first.<\/div>\n

In here, we create a keyup function when user start typing in their form. Then,\u00a0seize 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.<\/p>\n

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

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.<\/p>\n

Now, we have to apply Chart.js\u00a0into our website. Parse the json value as object and make variables to the color.<\/p>\n

\/\/ parse json value as obj\r\nobj = JSON.parse(myJSON);\r\n\r\n\/\/ console.log(obj);\r\n\r\n\/\/pie\r\nvar ctx = $('#piechart')[0].getContext('2d');\r\n\/\/bar\r\nvar ctx2 = $('#barchart')[0].getContext('2d');\r\n\r\n\/\/both\r\nvar ChartColor = [\r\n    window.chartColors.red,\r\n    window.chartColors.purple,\r\n    window.chartColors.yellow,\r\n    window.chartColors.green,\r\n    window.chartColors.blue\r\n];\r\n\r\nvar ChartLabels = [\"Red\", \"Purple\", \"Yellow\", \"Green\", \"Blue\"];\r\n\r\nvar ChartData = [\r\n     window.obj.red,\r\n     window.obj.purple,\r\n     window.obj.yellow,\r\n     window.obj.green,\r\n     window.obj.blue\r\n];\r\n\r\n        \/\/fix the bug\r\n        if(window.myPie != undefined){\r\n            window.myPie.destroy();\r\n        }\r\n\r\n\r\n        \/\/pie\r\n        window.myPie = new Chart(ctx, {\r\n                type: 'pie',\r\n                data: {\r\n                    labels: ChartLabels,\r\n                    datasets: [{\r\n                        data: ChartData,\r\n                        backgroundColor: ChartColor,\r\n                    }]\r\n                },\r\n                options: {\r\n                    title: {\r\n                        display: true,\r\n                        text: 'Pie Chart'\r\n                    }\r\n                }\r\n        });\r\n\r\n        \r\n\r\n        \/\/fix the bug\r\n        if(window.myBar != undefined){\r\n            window.myBar.destroy();\r\n        }\r\n\r\n        \/\/bar\r\n        window.myBar = new Chart(ctx2, {\r\n                type: 'bar',\r\n                data: {\r\n                    labels: ChartLabels,\r\n                datasets: [{\r\n                    data: ChartData,\r\n                    backgroundColor: ChartColor,\r\n                }],\r\n                },\r\n                options: {\r\n                    legend: {\r\n                        display: false\r\n                    },\r\n                    title: {\r\n                        display: true,\r\n                        text: 'Bar Chart'\r\n                    }\r\n                }\r\n\r\n            });<\/pre>\n

That’s it! You final html and javascript files should look like below.<\/p>\n

index.html<\/strong><\/em><\/p>\n

<!doctype html>\r\n<html>\r\n\r\n<head>\r\n<title>My Chart<\/title>\r\n \r\n\r\n<!-- bootstrap css-->\r\n<link rel=\"stylesheet\" href=\"css\/bootstrap.min.css\">\r\n<link rel=\"stylesheet\" href=\"css\/bootstrap-theme.min.css\" >\r\n<!-- custom css -->\r\n<link rel=\"stylesheet\" href=\"css\/style.css\" >\r\n\r\n<!-- jquery -->\r\n<script src=\"js\/jquery-3.1.1.min.js\"><\/script>\r\n\r\n<!-- bootstrap js-->\r\n<script src=\"js\/bootstrap.min.js\" ><\/script>\r\n\r\n<!-- chart.js js -->\r\n<script src=\"js\/Chart.bundle.min.js\"><\/script>\r\n<script src=\"js\/Chart.min.js\"><\/script>\r\n<script src=\"js\/utils.js\"><\/script>\r\n\r\n<\/head>\r\n<body>\r\n<div class=\"column\">\r\n<h4 class=\"text-center\">Please Type the Number<\/h4>\r\n    <div class=\"row\">\r\n        <div class=\"col-xs-4\">\r\n<!-- You form start here... -->\r\n            <form id=\"myForm\">\r\n            <div class=\"form-group\">\r\n                <label for=\"red\" >ChartColors.Red<\/label>\r\n                <input type=\"number\" step=\"any\" class=\"form-control\" id=\"red\" name=\"red\"  >\r\n            <\/div>\r\n            <div class=\"form-group\">\r\n                <label for=\"purple\" >ChartColors.Purple<\/label>\r\n                <input type=\"number\" step=\"any\" class=\"form-control\" id=\"purple\" name=\"purple\"  >\r\n            <\/div>\r\n            <div class=\"form-group\">\r\n                <label for=\"yellow\" >ChartColors.Yellow<\/label>\r\n                <input type=\"number\" step=\"any\" class=\"form-control\" id=\"yellow\" name=\"yellow\"   >\r\n            <\/div>\r\n            <div class=\"form-group\">\r\n                <label for=\"green\" >ChartColors.Green<\/label>\r\n                <input type=\"number\"step=\"any\" class=\"form-control\" id=\"green\" name=\"green\" >\r\n            <\/div>\r\n             <div class=\"form-group\">\r\n                <label for=\"blue\" >ChartColors.Blue<\/label>\r\n                <input type=\"number\" step=\"any\" class=\"form-control\" id=\"blue\" name=\"blue\"  >\r\n            <\/div>\r\n            <\/form>\r\n<\/div>\r\n<!-- display charts with HTML5 canvas -->\r\n        <div class=\"col-xs-8\">\r\n            <div class=\"col-xs-6\">\r\n                <canvas id=\"barchart\"><\/canvas>\r\n                <div id=\"div2\"><\/div>\r\n            <\/div>\r\n\r\n            <div class=\"col-xs-6\">\r\n                <canvas id=\"piechart\"><\/canvas>\r\n            <\/div> \r\n            \r\n        <\/div>\r\n        <\/div>\r\n<\/div>\r\n\r\n<!-- chartjs start here -->\r\n<script src=\"js\/mychart.js\" ><\/script><\/pre>\n

mychart.js<\/strong><\/em>
\n<\/p>\n

\/\/ typing function...\r\n$(\"input\").keyup(function(){\r\n\r\n\/\/ request form array values\r\n$.fn.extend = function(){\r\n               \r\nvar formData = {}; \r\nvar formArray = $('#myForm').serializeArray();  \r\n  for(var i = 0 ; i < formArray.length; i++){\r\n    formData[formArray[i].name] = formArray[i].value;\r\n  }\r\n  return formData;\r\n\r\n};  \r\n\r\n\/\/ convert to JSON data\r\nvar myJSON = JSON.stringify($('form').extend())\r\n\r\n\/\/ Retrieve the Pie and Bar chart JSON data via Ajax HTTP GET requests.\r\n$.ajax({\r\n  url: 'index.html',\r\n  type: 'GET',\r\n  data: myJSON,\r\n  success: function () {\r\n    \/\/Do stuff with the JSON data\r\n    $(\"#div2\").html(\"<h4><br>\"+myJSON.split(\",\").join(\", <br><br>\")+\"<\/h4>\")\r\n  },\r\n  error: function () {\r\n    $(\"#div2\").html(\"<h4>Ajax Request Failed. <br><br> Please make sure you are using webserver.<\/h4>\")\r\n  }\r\n});\r\n\r\n\r\n\/\/ parse json value as obj\r\nobj = JSON.parse(myJSON);\r\n\r\n\/\/ console.log(obj);\r\n\r\n\/\/pie\r\nvar ctx = $('#piechart')[0].getContext('2d');\r\n\/\/bar\r\nvar ctx2 = $('#barchart')[0].getContext('2d');\r\n\r\n\/\/both\r\nvar ChartColor = [\r\n    window.chartColors.red,\r\n    window.chartColors.purple,\r\n    window.chartColors.yellow,\r\n    window.chartColors.green,\r\n    window.chartColors.blue\r\n];\r\n\r\nvar ChartLabels = [\"Red\", \"Purple\", \"Yellow\", \"Green\", \"Blue\"];\r\n\r\nvar ChartData = [\r\n     window.obj.red,\r\n     window.obj.purple,\r\n     window.obj.yellow,\r\n     window.obj.green,\r\n     window.obj.blue\r\n];\r\n\r\n        \/\/fix the bug\r\n        if(window.myPie != undefined){\r\n            window.myPie.destroy();\r\n        }\r\n\r\n\r\n        \/\/pie\r\n        window.myPie = new Chart(ctx, {\r\n                type: 'pie',\r\n                data: {\r\n                    labels: ChartLabels,\r\n                    datasets: [{\r\n                        data: ChartData,\r\n                        backgroundColor: ChartColor,\r\n                    }]\r\n                },\r\n                options: {\r\n                    title: {\r\n                        display: true,\r\n                        text: 'Pie Chart'\r\n                    }\r\n                }\r\n        });\r\n\r\n        \r\n\r\n        \/\/fix the bug\r\n        if(window.myBar != undefined){\r\n            window.myBar.destroy();\r\n        }\r\n\r\n        \/\/bar\r\n        window.myBar = new Chart(ctx2, {\r\n                type: 'bar',\r\n                data: {\r\n                    labels: ChartLabels,\r\n                datasets: [{\r\n                    data: ChartData,\r\n                    backgroundColor: ChartColor,\r\n                }],\r\n                },\r\n                options: {\r\n                    legend: {\r\n                        display: false\r\n                    },\r\n                    title: {\r\n                        display: true,\r\n                        text: 'Bar Chart'\r\n                    }\r\n                }\r\n\r\n            });\r\n\r\n\r\n});  \/\/ type function end<\/pre>\n

For more information, please visit the Chart.JS API Documentation<\/a>\u00a0to customize.<\/p>\n

Thanks!<\/p>\n

Reference featured image: http:\/\/www.chartjs.org\/<\/a><\/span><\/p>\n","protected":false},"excerpt":{"rendered":"

In recent, data visualization becomes more important\u00a0be … Continue reading “Simple data visualization with HTML5 form and Chart.js”<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":460,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"footnotes":""},"categories":[68],"tags":[35,66,65,64,67,39,36,60],"_links":{"self":[{"href":"https:\/\/smartlun.com\/wp-json\/wp\/v2\/posts\/459"}],"collection":[{"href":"https:\/\/smartlun.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/smartlun.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/smartlun.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/smartlun.com\/wp-json\/wp\/v2\/comments?post=459"}],"version-history":[{"count":0,"href":"https:\/\/smartlun.com\/wp-json\/wp\/v2\/posts\/459\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/smartlun.com\/wp-json\/wp\/v2\/media\/460"}],"wp:attachment":[{"href":"https:\/\/smartlun.com\/wp-json\/wp\/v2\/media?parent=459"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/smartlun.com\/wp-json\/wp\/v2\/categories?post=459"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/smartlun.com\/wp-json\/wp\/v2\/tags?post=459"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}