allgood
allgood

Reputation: 3

google charts graph view on page load

I realized graphic on my web page with using google charts library. it adds to the page by AJAX, into <div>.

I want to show graph when page load, for this i write:

<script type="text/javascript">

    window.onload =function()
    {
      callgraph();
    }         
</script>

callgraph- my function to draw the graph.

function callgraph() {
    var msg   = $('#formx').serialize();
    $.ajax({
      type: 'POST',
      url: '/graph/data',
      data: msg,
      success: function(data) {
        $('#results').html(data);
      },
      error:  function(xhr, str){
      //  alert('xhr.responseCode);
      }
    });
}

It works, but sometimes graph does not load when I refresh the page. When I change data at form, and call my function, it always work normally.

Then I call my function two times with delay.Using this method graph appears all times.

 window.onload =function(){ 
    setTimeout(callgraph, 250);callgraph();
 }

But I think it's not good way, to call function two times.

drawChart function

 <script type="text/javascript">
  	
 google.charts.load('current', {'packages':['line'],callback: drawChart});

 function drawChart() {
     var data = new google.visualization.DataTable();
     data.addColumn('string', 'Day'); 
     data.addColumn('number', 'Heads');
     data.addRows([

     <?php

     while($row = mysqli_fetch_array($data))
     {  
         echo '[ \''.$row['Date'].'\' , ';     
         echo $row['HeadCount'].'  ],';      
     }
     ?>
     ]);

     var options = {
         title: '',
         height: 640,
         vAxis: {
             viewWindow: {
                 min: 0,
             }
         },
     };

     var chart = new google.charts.Line(document.getElementById('chart_div'));
     chart.draw(data, google.charts.Line.convertOptions(options));
}
</script>

Can you advise what to do?

Upvotes: 0

Views: 1342

Answers (1)

Eduardo Balbinot
Eduardo Balbinot

Reputation: 139

We can't know the code that comes from your ajax request, but it sounds like you're trying to draw the chart before google api gets fully loaded. Please keep in mind that you should always draw the chart using the callback provided by the api, like this:

google.charts.setOnLoadCallback(drawChart);

That's probably the reason the chart loads after some timeout.

Upvotes: 1

Related Questions