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


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



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


How to make this … ?


Create HML File

Create grafik.html and insert this code:

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

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


  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;
	xhttp.open("GET", "/data_stock_masuk", true);

 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)]);

	var options = {'title':'How Much Total Stock In Daily',

        var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
        chart.draw(data, options);

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


  • 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 *