Search code examples
javascriptarraysloopsbar-chartmorris.js

JavaScript: BarChart populate data using loop


Hello there I have a problem populating javascript barchart from my database I am using a morris.js barchart the code of my html is below:

<div class="chart" id="bar-chart" style="height: 300px;"></div>

the javascript:

  <script>
  

$(function () {
  "use strict";    
  //BAR CHART
  var month = <?php echo json_encode($result_array, JSON_HEX_TAG); ?>;
  var salary = <?php echo json_encode($result_array2, JSON_HEX_TAG); ?>;
  var bar = new Morris.Bar({
      element: 'bar-chart',
      resize: true,
      data: [
        {y: month, a: salary},

       ]
      ,
      barColors: ['#00a65a', '#f56954'],
      xkey: 'y',
      ykeys: ['a'],
      labels: ['Date', 'Total'],
      hideHover: 'auto'

  });
  
  
});

The PHP code:

  <?php 
   $q  = mysqli_query($con,"SELECT * FROM salary_logs 
   ORDER BY id ASC LIMIT 5");
    $result_array = array();
    while($row = mysqli_fetch_assoc($q))
   {
     $result_array[] = $row['month'];
     $result_array2[] = $row['salary'];
     echo json_encode($result_array, JSON_HEX_TAG);
   }
  ?>

The data in my database are :

month: january , february

salary: 1000,2000

Is there any way to create a loop that will automatically add those data? Example the next month data will be :

month: january, february, march

salary: 1000, 2000, 3000


Solution

  • Easy way to do this (maybe not the perfect solution but works fine and easy to handle) -

    Declare a php variable for chart data (above while loop) like - $chart_data = '';

    Next inside the while loop do -

    $chart_data = ''; // variable for chart data
    
    while($row = mysqli_fetch_assoc($q))
    {
        $chart_data .= "{ y: '" . $row['month'] . "', a: " . $row['salary'] . " },";
    }
    

    Now echo $chart_data inside JavaScript function. like-

    data: [ <?php echo $chart_data; ?> ],
    

    Full JavaScript Function

    $(function() {
        "use strict";
        //BAR CHART
        var month = <?php echo json_encode($result_array, JSON_HEX_TAG); ?>;
        var salary = <?php echo json_encode($result_array2, JSON_HEX_TAG); ?>;
        var bar = new Morris.Bar({
            element: 'bar-chart',
            resize: true,
    
            data: [ <?php echo $chart_data; ?> ],
    
            barColors: ['#00a65a', '#f56954'],
            xkey: 'y',
            ykeys: ['a'],
            labels: ['Date', 'Total'],
            hideHover: 'auto'
    
        });    
    
    });