ajaxchartsgoogle-visualizationredraw

Google chart does not redraw the chart based on a new Ajax filter


How can I make this code update the google chart with new Ajax call data? When I submit from the dropdown list I see the updated data in the echoed results but the chart does not update. It seems like I have place the submit code in the wrong place.

<title>Google Chart in PHP and MySQL</title>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

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

  <script type="text/javascript">


  var drawChart;

      $(document).ready(function () {

                $.ajax({
                      url: "datagen2_2.php",
                      dataType: "JSON",
                      success: function (result) {google.charts.load('current', {'packages': ['corechart']});
                      google.charts.setOnLoadCallback(function () {drawChart(result);
                      });
                }
          
          
      });

      $(".submit").click(function() {

                $.ajax({
                      url: "datagen2_2.php",
                      dataType: "JSON",
                      success: function (result) {google.charts.load('current', {'packages': ['corechart']});
                      google.charts.setOnLoadCallback(function () {drawChart(result);
                      });
                    }
                });
       });


  function drawChart(result) {

      var data = new google.visualization.DataTable();
      data.addColumn('string', 'Gender');
      data.addColumn('number', 'HowMany');

      var dataArray = [];

      $.each(result, function (i, obj) {
            dataArray.push([obj.Gender, parseInt(obj.HowMany)]);
      });

      data.addRows(dataArray);

      var piechart_options = {
            title: 'Gender breakdown',
            width: 470,
            height: 270,
            colors: ['#800080', '#b200ff']
      };

      var piechart = new google.visualization.PieChart(document.getElementById('piechart_div'));
      piechart.draw(data, piechart_options);
      }
      });




    </script>

  </head>
  <body>
  <center>
      <img src="logo.png" style="width:200px;height:60px;">
  </center>
  <hr style="border: 4px solid blue;" />

      <table class="columns" style="width:120%">
      <tr>
          <td>
          <label>Gender filter</label>
          <?php

          //Connect to our MySQL database using the PDO extension.
          $pdo = new PDO('mysql:host=localhost;dbname=panel', 'root', '');

          //Our select statement. This will retrieve the data that we want.
          $sql = "SELECT DISTINCT Gender FROM employee GROUP BY Gender";

          //Prepare the select statement.
          $stmt = $pdo->prepare($sql);

          //Execute the statement.
          $stmt->execute();

          //Retrieve the rows using fetchAll.
          $Ngender = $stmt->fetchAll();

          ?>



  <!--Start here -->
      <form method="post" action="indexdash2.php">
    
          <select name="filter">
              <option value="" disabled selected hidden>Choose a filter</option>
              <?php foreach($Ngender as $Ngender): ?>
                  <option value="<?= $Ngender['Gender']; ?>"><?= $Ngender['Gender']; ?></option>
              <?php endforeach; ?>
          </select>
          <input type="submit" name="submit" value="Find">
      </form>
          </td>


      </table>
  <hr style="border: 4px solid blue;" />




  <h2>DEMOGRAPHICS</h2>
      <table class="columns">
          <tr>  
              <td>
                  <div id="piechart_div" style="border: 1px solid #ccc"></div>
              </td>
          </tr>
    
      </table>



  </body>
  </html>

Any help will be appreciated! I am pretty sure I have missed something basic as I am new to this.


Solution

  • first, google's load method only needs to be called once per page load.
    afterwards, you can draw the chart, or charts, as many times as needed.

    next, google's load method will also wait on the page to load by default.
    so we can use load in place of jquery's ready method.

    recommend loading google first,
    then make the call to get the data and draw the chart.

    see following snippet...

    google.charts.load('current', {
      packages: ['corechart']
    }).then(function () {
    
      function getData() {
        $.ajax({
          url: "datagen2_2.php",
          dataType: "JSON"
        }).done(function (result) {
          drawChart(result);
        });
      }
    
      $('.submit').click(getData);
      getData();
    
      function drawChart(result) {
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Gender');
        data.addColumn('number', 'HowMany');
    
        $.each(result, function (i, obj) {
          data.addRow([obj.Gender, parseInt(obj.HowMany)]);
        });
    
        var piechart_options = {
          title: 'Gender breakdown',
          width: 470,
          height: 270,
          colors: ['#800080', '#b200ff']
        };
    
        var piechart = new google.visualization.PieChart(document.getElementById('piechart_div'));
        piechart.draw(data, piechart_options);
      }
    
    });