Display Daily Dynamic Data Using Google Line Chart And AJAX

Before Started

You should read this if you want to get daily data from MySQL

Known

The data is provided with json type in “http://localhost:3000/data_stock_masuk” like this one below:

{"data_stock":[{"time_create":"2019-09-15T13:28:10.000Z","angka_hari":1,"nama_hari":"Sunday","jumlah":20},{"time_create":"2019-09-16T13:28:10.000Z","angka_hari":2,"nama_hari":"Monday","jumlah":20},{"time_create":"2019-09-17T13:28:41.000Z","angka_hari":3,"nama_hari":"Tuesday","jumlah":30},{"time_create":"2019-09-18T13:28:41.000Z","angka_hari":4,"nama_hari":"Wednesday","jumlah":40},{"time_create":"2019-09-19T13:29:10.000Z","angka_hari":5,"nama_hari":"Thursday","jumlah":50}]}

Wanted

I want to get json data above and display it in Line Chart like image below:

Question:

How to make this … ?

Answer:

Create HML File

Create grafik.html and insert this code:

<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>  
<script type="text/javascript">

      google.charts.load('current', {'packages':['corechart']});

      google.charts.setOnLoadCallback(ajx);

  function ajx(){
	 
	var xhttp = new XMLHttpRequest();
 
    xhttp.onreadystatechange = function() {
    if (this.readyState == XMLHttpRequest.DONE && this.status == 200) {
	
	let resJson=JSON.parse(this.responseText)
        let data=resJson.data_stock;
	drawChart(data);	
    }
  };
	
	xhttp.open("GET", "/data_stock_masuk", true);
	 
	xhttp.send();
	  
}

 function drawChart(dt) {
	  
       
        var data = new google.visualization.DataTable();
		
        data.addColumn('string', 'Daily');
        data.addColumn('number', 'Total Stock In');
		
	var chartData = [];

	for(var idx = 0; idx < dt.length; idx++) {
            var item = dt[idx];
	    chartData.push([item.nama_hari, parseInt(item.jumlah)]);
        }

	data.addRows(chartData);
	var options = {'title':'How Much Total Stock In Daily',
                       'width':400,
                       'height':300};

        
        var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>
 </head>

  <body>
   <div id="chart_div"></div>
  </body>
</html>

Explain:

  • google.charts.setOnLoadCallback(ajx), this code mean run the ajx function when google charts API has been loaded
  • JSON.parse(this.responseText) returns JSON object from responseText
  • let data=resJson.data_stock is for get data_stock object and give it to data variable
  • chartData.push([item.nama_hari, parseInt(item.jumlah)]), this code for adding data to chartData array

Thanks for reading

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *