Redrawing a google pie chart with an AJAX call

4,127 views
Skip to first unread message

phi16181

unread,
May 18, 2014, 7:07:12 PM5/18/14
to google-visua...@googlegroups.com
I am using the following pie chart code that is being fed data from a query:

 <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Customers', 'Status'],
          ['Accepted',     <?php echo $rowsaccepted ;?>],
          ['Declined',      <?php echo $rowsdeclined;?>],
          ['Not Reviewed',  <?php echo $rowsnreview;?>]
        ]);

        var options = {
                       'width':200,
                       'height':200,
                       'backgroundColor':'#474747',
                       'legend': 'none',
                       'chartArea':{left:20,top:0,width:250,height:250},
                       colors: ['#ef8200', '#007fc2', '#41cf0f'],
                       fontSize:14,

                   };

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


and the following AJAX call that updates my DB upon clicking a button; therefore updating the cart data, but I must refresh the page for the chart to refresh:

<script type="text/javascript">
$(function() {
$(".decline").click(function(){
  
var element = $(this);
var del_id = element.attr("id1");
var order_id = element.attr("data-order1");
 $.ajax({
   type: "POST",
   url: "decline.php",
   data: {id1:del_id,order_id1:order_id},
   success: function(){cache: false}
});
  $(this).parents(".show").animate({ backgroundColor: "#003" }, "slow")
  .animate({ opacity: "hide" }, "slow");

});
});
</script>

Is there any way I can add a call in my AJAX function that will refresh and redraw the pie chart without requiring the page to be refreshed?

Thanks!

Andrew Gallant

unread,
May 18, 2014, 9:56:53 PM5/18/14
to google-visua...@googlegroups.com
You need to set up a data source on your server that serves up the data for your chart.  Something like this should work:

// code to access database and populate the $rowsaccepted, $rowsdeclined, and $rowsnreview variables up here
$myData = array(

    array('Customers', 'Status'),
    array('Accepted', $rowsaccepted)
,
    array('Declined', $rowsdeclined)
,
    array('Not Reviewed', $rowsnreview)

);
echo json_encode($myData, JSON_NUMERIC_CHECK);


Rewrite your chart function like this:

function drawChart() {
    $.ajax({
        url: '/path/to/data/source/',
        dataType: 'json',
        success: function (json) {
            var data = google.visualization.arrayToDataTable(json);

           
            var options = {
                width: 200,
                height: 200,
                backgroundColor: '#474747',
                legend: 'none',
                chartArea: {left: 20, top: 0, width: 250, height: 250},

                colors: ['#ef8200', '#007fc2', '#41cf0f'],
                fontSize: 14
            };
   
            var chart = new google.visualization.PieChart(document.getElementById('piechart'));
            chart.draw(data, options);
        }
    });
}


You can then call the drawChart function whenever you want to redraw the chart.

phi16181

unread,
May 26, 2014, 8:07:08 PM5/26/14
to google-visua...@googlegroups.com
Ok thanks for the input; here is what I have so far:


I am trying to use the following AJAX call to update a google chart when a user clicks on a button:

    function drawChart() {
        $.ajax({
            url: 'includes/cust_view_det/customer_view_det_chartsql.php',
            dataType: 'json',
            success: function (json) {
                var data = google.visualization.arrayToDataTable(json);
    
                
                var options = {
                    width: 200,
                    height: 200,
                    backgroundColor: '#474747',
                    legend: 'none',
                    chartArea: {left: 20, top: 0, width: 250, height: 250},
    
                    colors: ['#ef8200', '#007fc2', '#41cf0f'],
                    fontSize: 14
                };
        
                var chart = new google.visualization.PieChart(document.getElementById('piechart'));
                chart.draw(data, options);
            }
        });
    }
    $("#update").click(drawChart);

Here is the file that feeds the AJAX URL:

    $result_accept = "SELECT * FROM mgap_orders WHERE mgap_accept = 1 AND account_manager_id = '" . $_SESSION['account_manager_id'] . "' ";
    $stmtacc = $pdo->prepare($result_accept); 
    $stmtacc->execute();
    $rowsaccepted = $stmtacc->rowCount();
    
    $result_decline = "SELECT * FROM mgap_orders WHERE mgap_decline = 2 AND account_manager_id = '" . $_SESSION['account_manager_id'] . "' ";
    $stmtdec = $pdo->prepare($result_decline); 
    $stmtdec->execute();
    $rowsdeclined = $stmtdec->rowCount();
    
    $result_nreview = "SELECT * FROM mgap_orders WHERE mgap_nr = 3 AND account_manager_id = '" . $_SESSION['account_manager_id'] . "' ";
    $stmtnr = $pdo->prepare($result_nreview); 
    $stmtnr->execute();
    $rowsnreview = $stmtnr->rowCount();
    
    $myData = array(
        array('Customers', 'Status'),
        array('Accepted', $rowsaccepted),
        array('Declined', $rowsdeclined),
        array('Not Reviewed', $rowsnreview)
    );
    echo json_encode($myData, JSON_NUMERIC_CHECK);

and here is the button:

    <button type="button" id="update">Update Chart</button>

The chart updates just as it should if the page is refreshed, but I cannot single out the issue with my AJAX call to make it work when the button is clicked.


Any help is appreciated.

phi16181

unread,
May 26, 2014, 8:33:39 PM5/26/14
to google-visua...@googlegroups.com
BTW I can also use setRefreshInterval instead of the AJAX call if someone could show me how to use it!

Andrew Gallant

unread,
May 26, 2014, 10:05:14 PM5/26/14
to google-visua...@googlegroups.com
setRefreshInterval is a method of the Query class, which requires a lot more coding server-side to implement, and doesn't really get you anything you can't get without it.  Calling setInterval(drawChart, interval); in javascript would be quicker and not involve any more server-side coding.

I don't know why your button click isn't working.  Open the page in Chrome, and open the developer's console (ctrl+shift+j to open in windows) to check for error messages when you click the update button.  If there are no error messages, check the network tab to see if any requests are sent to the server when you click the button.  If there are no requests sent to the server, try adding this:

$("#update").click(function () {
    console.log('button clicked');
});


You can enter that directly in the developer's console.  You should see that message in the console whenever the button is clicked (or it may increment a number next to the message if nothing else happened in between).  If that's not working, then something very strange is going on.

Richard Davy

unread,
Jan 10, 2016, 11:57:02 AM1/10/16
to Google Visualization API
Hey this is great information, worked like a charm
Reply all
Reply to author
Forward
0 new messages