Dynamic google chart generation using php

2,040 views
Skip to first unread message

Imraan Nasir

unread,
Jun 14, 2017, 5:31:42 PM6/14/17
to Google Visualization API
The following is the code that I basically want to implement using a loop function:

  function drawChart() {
  
    var data1 = google.visualization.arrayToDataTable(<?php echo $mychartdatax1 ?>);
    var data2 = google.visualization.arrayToDataTable(<?php echo $mychartdatax2 ?>);
    var data3 = google.visualization.arrayToDataTable(<?php echo $mychartdatax3 ?>);
    var data4 = google.visualization.arrayToDataTable(<?php echo $mychartdatax4 ?>);
   var data5 = google.visualization.arrayToDataTable(<?php echo $mychartdatax5 ?>);
   
  var options = {
   colors: ['#FFA500'],
   legend: {position:'none'},
  };
 
  var chart1 =  new google.visualization.ColumnChart(document.getElementById('chart_div1'));
  var chart2 =  new google.visualization.ColumnChart(document.getElementById('chart_div2'));
  var chart3 =  new google.visualization.ColumnChart(document.getElementById('chart_div3'));
  var chart4 =  new google.visualization.ColumnChart(document.getElementById('chart_div4'));
  var chart5 =  new google.visualization.ColumnChart(document.getElementById('chart_div5'));
  
  setTimeout(function(){chart1.draw(data1, options);},10);
  setTimeout(function(){chart2.draw(data2, options);},10);
  setTimeout(function(){chart3.draw(data3, options);},10);
  setTimeout(function(){chart4.draw(data4, options);},10);
  setTimeout(function(){chart5.draw(data5, options);},10);

      
 }

I am drawing an unknown number of charts the charts divs are named via php and are generated on the page, the data is stored in the variable format as shown above, the problem exists when I try to loop through and pull the data I keep running into an error. Please assist.

Daniel LaLiberte

unread,
Jun 14, 2017, 7:34:07 PM6/14/17
to Google Visualization API
Hi Imraan,

It would be best if you could point to a page with the generated HTML and JavaScript rather than have us guess what your PHP code is doing.

--
You received this message because you are subscribed to the Google Groups "Google Visualization API" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-visualization-api+unsub...@googlegroups.com.
To post to this group, send email to google-visualization-api@googlegroups.com.
Visit this group at https://groups.google.com/group/google-visualization-api.
To view this discussion on the web visit https://groups.google.com/d/msgid/google-visualization-api/c90abe1c-cb04-4ecf-9fcb-caa08cf05bcd%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--

Imraan Nasir

unread,
Jun 16, 2017, 5:18:12 PM6/16/17
to Google Visualization API
Apologies I will show you what I want to do and then you'll let me know if this is possible. You see the multiple instances of each chart above, what I want to do is place that into a loop so that I can pull php variable data and place it in assigned place holders eg.

google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
      var data = new Array();
      var chart = new Array(); 
      <?php echo $mycount2 =1; ?>; 
      for ( var i = 1; i = <?php echo $mycount; ?>; i++) {
  
         var data[i]  = google.visualization.arrayToDataTable(<?php echo ${"mychartdatax".$mycount2} ?>);
        var options = {
                         colors: ['#FFA500'],
                         legend: {position:'none'},
          };
   var chart[i]  =  new google.visualization.ColumnChart(document.getElementById('chart_div'+i));

   chart[i].draw(data[i], options);
       <?php echo $mycount2 =$mycount2+1; ?>; 
   }
}


php mycount stores the number of charts to be generated
php mycount2 sets a variable as a counter to 1
php mychartdatax (looks for an appended number after it I can generate each of these and the data is stored properly so no error there)
php mycount2 one is added to further the loop on the next instance
chart_div+i  is correctly named in php to be chart_div1 chart_div2 etc.

Is this possible? Please shed some light I will put up anything else you require but I think this should let you know what I am attempting to do.

Daniel LaLiberte

unread,
Jun 16, 2017, 5:26:49 PM6/16/17
to Google Visualization API
It seems your question is really more about php than Google Charts.   Maybe someone here who knows php can help you with that.

--
You received this message because you are subscribed to the Google Groups "Google Visualization API" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-visualization-api+unsub...@googlegroups.com.
To post to this group, send email to google-visualization-api@googlegroups.com.
Visit this group at https://groups.google.com/group/google-visualization-api.

For more options, visit https://groups.google.com/d/optout.

Imraan Nasir

unread,
Jun 17, 2017, 6:49:03 AM6/17/17
to Google Visualization API
Actually it's a JavaScript question about the Goggle Charts Code trying to make a loop to create multiple dynamic graphs with dynamic placeholders, I can handle the php what I want to know is what is the code to create the different graphs in a loop can you give me a simple example because it seems the syntax I am using is incorrect and not allowing anything to be generated.

Ray Thomas

unread,
Jun 17, 2017, 9:49:08 AM6/17/17
to Google Visualization API
I didn't answer before as I don't know enough about PHP to help you with any code, but what you want to do is surprisingly straightforward.

Create an array to hold your variables
Loop through that to create the HTML, create the query to Google Visualizations and draw the graphs.

There's something I've been working on at https://jsfiddle.net/brisray/2a3rmwgu/

There's one thing I'm not sure about. My code cannot capture the graph ready event. I do not know why. The original code looks like it should have been able to to ensure the graph is drawn before it moves on to the next function - but it doesn't. As a temporary measure I added a small 1/10 of a second delay to ensure the graph is drawn before the user in my code is able to manipulate the graphs.

Ray Thomas

unread,
Jun 17, 2017, 10:00:02 AM6/17/17
to Google Visualization API
One problem you might run into depending on the size of your data.

My JS array keeps a copy of the datatable so they can be reused to redraw the graphs. I should imagine if you do that with a lot of large tables you'll run into memory problems. As you're using PHP one solution might be to write the tables to the server and fetch them from there.

Ray 

Imraan Nasir

unread,
Jun 18, 2017, 11:22:19 AM6/18/17
to Google Visualization API
Progress has been made, I think now the issue could be a PHP one the following generates the place holders and graphs for each but unfortunately it's all the same graph and data it is as though the data call is not changing the variable name on the ned in order to create a new query. the following is the code that is semi-working:

<script type="text/javascript">

google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
 function drawChart() {
     for (var i =1; i<=<?php echo $mycount ?>; i++){
      var data = google.visualization.arrayToDataTable(<?php echo ${"mychartdatax".$myvar++}; ?>);
      var options = { colors: ['#FFA500'],legend: {position:'none'},};
      var chart =  new google.visualization.ColumnChart(document.getElementById("chart_div"+i));
      chart.draw(data, options);
 
   }

  }
</script>

The part that pulls in the data seems stuck with $myvar being initialized in the php above this code to be 1, and it goes through the loop but it seems to be only incrementing once and then stopping. Its either that or the generation of the singular chart.draw(data,options) instance keeps rewriting the generated graphs to the last one, but I caputured the loop it is supposed to go through 3 times but the variable only makes it as far as 2. I am lost

Imraan Nasir

unread,
Jun 18, 2017, 4:34:25 PM6/18/17
to Google Visualization API
Further Progress has been made, the following is the JavaScript code:

<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
  function drawChart() {
   var data = "";
   var options2 = "";
   var chart = "";

 for (var i =1; i<=<?php echo $mycount; ?>; i++){
   <?php foreach($mychartarray as $key => $val){ ?>
   data = new google.visualization.arrayToDataTable(<?php echo $val; ?>);
    options2 = { colors: ['#FFA500'],legend: {position:'none'}, title:'Graph '+i,};

    chart =  new google.visualization.ColumnChart(document.getElementById("chart_div"+i));
    chart.draw(data,options2);
   
   
    <?php } ?>
   }
 
  }
</script>

This is what the browser spits out:

 function drawChart() {
   var data = "";
   var options2 = "";
   var chart = "";
 for (var i =1; i<=3; i++){
      data = new google.visualization.arrayToDataTable([["Label","Value"],["January",0],["February",0],["March",12],["April",0],["May",0],["June",0],["July",0],["August",46],["September",0],["October",0],["November",0],["December",0]]);
    options2 = { colors: ['#FFA500'],legend: {position:'none'}, title:'Graph '+i,};

    chart =  new google.visualization.ColumnChart(document.getElementById("chart_div"+i));
    chart.draw(data,options2);
   
   
       data = new google.visualization.arrayToDataTable([["Label","Value"],["January",0],["February",0],["March",45],["April",0],["May",0],["June",0],["July",0],["August",0],["September",0],["October",0],["November",0],["December",0]]);
    options2 = { colors: ['#FFA500'],legend: {position:'none'}, title:'Graph '+i,};

    chart =  new google.visualization.ColumnChart(document.getElementById("chart_div"+i));
    chart.draw(data,options2);
   
   
       data = new google.visualization.arrayToDataTable([["Label","Value"],["January",0],["February",0],["March",0],["April",0],["May",0],["June",0],["July",0],["August",0],["September",0],["October",0],["November",0],["December",0]]);
    options2 = { colors: ['#FFA500'],legend: {position:'none'}, title:'Graph '+i,};

    chart =  new google.visualization.ColumnChart(document.getElementById("chart_div"+i));
    chart.draw(data,options2);
   
   
       }
}

Don't know if this helps anymore

Imraan Nasir

unread,
Jun 18, 2017, 4:35:31 PM6/18/17
to Google Visualization API
What keeps happening is the same graph is generated for all 3 instances of the graph

Daniel LaLiberte

unread,
Jun 18, 2017, 5:39:47 PM6/18/17
to Google Visualization API
The body of your loop for i is 1 to 3 is drawing 3 charts, all with the same id: chart_div + i.  So all three charts are drawn on top of the previous one for the first time through the loop when the id is chart_div1.  Then the second time the id is chart_div2 for all three charts.  

But it sounds like you only want 3 charts altogether.  If so, then you either want to get rid of the JavaScript for loop or the PHP foreach loop.


On Sun, Jun 18, 2017 at 4:35 PM, Imraan Nasir <imraan...@gmail.com> wrote:
What keeps happening is the same graph is generated for all 3 instances of the graph

--
You received this message because you are subscribed to the Google Groups "Google Visualization API" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-visualization-api+unsub...@googlegroups.com.
To post to this group, send email to google-visualization-api@googlegroups.com.
Visit this group at https://groups.google.com/group/google-visualization-api.

For more options, visit https://groups.google.com/d/optout.

Imraan Nasir

unread,
Jun 21, 2017, 6:31:40 AM6/21/17
to Google Visualization API
Thanks a million, I know its straightforward and simple but I have been looking at this damn thing for nearly a week now and it seems to have me fooled totally, it works great now thanks!!

Rajnikant Shukla

unread,
Oct 18, 2018, 8:13:24 AM10/18/18
to Google Visualization API
hi

i want draw multiple google bar chart in for loop .but draw only last graph with value.Please help me   

  <%int countv=1;%>
           
            var chart=""; 
            var data="";
            var options="";
          <c:forEach var="entry1" items="${ytdGraphMap}">
       
            <c:forEach var="hash1" items="${entry1['key']}">
            google.charts.load('current', {packages:['corechart']});
              google.charts.setOnLoadCallback(drawStuff);
            function drawStuff() {
                 data= new google.visualization.DataTable();
           
                data.addColumn('string', 'Country');
                data.addColumn('number', 'GDP');
                  data.addRows([
                    ['US', ${ytdGraphMap[hash1]}],
                    ['China', ${ytdGraphMap[hash1]}],
                    ['Japan', ${ytdGraphMap[hash1]}],
                    
                  ]);
    options = {
               title: 'GDP of selected countries, in US $millions',
               width: 300,
               height: 200,
               legend: 'none',
               bar: {groupWidth: '95%'},
               vAxis: { gridlines: { count: 4 } }
             };
     
             chart = new google.visualization.ColumnChart(document.getElementById('number_format_chart<%=countv%>'));
             chart.draw(data, options);
   
            };
                <%countv++;%>
                </c:forEach>
                </c:forEach>
Reply all
Reply to author
Forward
0 new messages