Dan Taylor
Dan Taylor

Reputation: 92

Using Google charts on a page called by AJAX

Hi All and thank you for your help in advance!

I have a customer reporting area that I have built and it uses Google charts to display data and this is all well and good and works fine (see image below). The issue I have is the the dropdown box used by admins to select a different client changes the page using ajax.

jQuery:

$("#adminCall").live("submit", function() {
    var fields = $(this).serialize();
        $.ajax({
                  type: 'POST',
                  url: '/ajax/admin-calls-ajax.php',
                  data: fields,
                  success: function(data)   
                  {     
                     $("#results").html(data);                   
                  }
            });
    return false;
});

The PHP file that is called is an exact replica of the file that displays correctly but passes the client ID as a post variable.

The Google Charts Code (on both files)

<script type="text/javascript">
  function drawVisualization() {
    // Create our data table out of JSON data loaded from server.
  var data = new google.visualization.DataTable(<?=$jsonTable?>);
  new google.visualization.ColumnChart(document.getElementById('visualization')).
        draw(data, {curveType: "function",
                    isStacked: true,
                    width: 780, height: 300,
                    fontSize: 10,
                    vAxis: {maxValue: <?php echo $maxval; ?>, minValue: 0}}
            );
  }
  google.setOnLoadCallback(drawVisualization);
  </script>
  <div id="visualization" style="width: 780px; height: 300px;"></div>

The javascript does not fire after the AJAX call and I guess I know that should be the case but can't think of a logical way around it as the JSON is generated by the PHP file that is called by AJAX.

Does anyone have any advice?

Image of graphs working correctly

Upvotes: 2

Views: 613

Answers (1)

SoWhat
SoWhat

Reputation: 5622

Does your ajax request go through(check Chrome document inspector>>network) before and after the ajax call. If it does

Try replacing google.setOnLoadCallback(drawVisualization); with drawVisualization() in the php file that sends the ajax code

google.setOnLoadCallback(drawVisualization) queues the method drawVisualization to be called when the page is loaded. In the usual web request/response flow this method is called after all the page elements i.e scripts, stylesheets images etc have been loaded.

When you call this via ajax, however, the page has already loaded and this call will never be made. Therefore calling the function directly with drawVisualization() is necessary.

Upvotes: 1

Related Questions