Jump to content

PHP variables in Google Chart


Ambienz

Recommended Posts

Hello,

 

Newbie needs some help pls. Searched far and wide, seen others ask but no answer (maybe too obvious).

 

I have a simple function to do some basic math (its for young children) 

 

                                                               <?php for($i=0;$i<$_POST['period'];$i++):       

                                                                $year=$current_year+$i;
                                                             
                                                                     // add contribution
                                                                     $total_contribution+=$_POST['contribution'];
                                                                     
                                                                     // interest in $ for the period
                                                                     $interest=$new_balance*($_POST['ROI']/100);
                                                                     $total_interest+=$interest;                                                                  
                                                                     
                                                                     // now new balance
                                                                      $new_balance=$new_balance+$interest-$cash+$_POST['contribution'];;
                                                                      $old_balance=$new_balance-$interest-$cash-$_POST['contribution'];;  
 
I use these results to propagate a dynamic table. Works fine.
 
Then I want to use the results to draw a Google chart
 
                                                       function drawChart() {
                                                        var data = new google.visualization.DataTable();
                                                            data.addColumn('string', 'Year');
                                                            data.addColumn('number', 'Balance');                                                    
 
                                                      for($i = 0; $i <= <?php echo @$_POST['period']?> ; $i++) {
                                                            data.addRows([
                                                              <?php
                                                                 echo "['" . $year . "'," . $balance . "],";
                                                               ?>
                                                            ]);
                                                        }                               
 
 
However all I end up with is a straight line chart on the first year and the final balance. It doesn't add a row of data for each iteration
 
Ive tried a lot of options but nothing seems to work.
 
Can anyone help me?
 
Thanks 
Edited by Ambienz
Link to comment
Share on other sites

Hi,

 

Here is the whole code.

<legend id="start">My Savings Calculator</legend>

    <table class="ccalc_table">
      <form method="post" action="" onsubmit="return validateInvCalc(this);">
      <tr>
            <td>How much do you currently have saved? :</td>
            <td><input name="invested_amount" type="number" pattern="\d*" placeholder="An amount" size="9" value="<?php echo @$_POST['invested_amount']?>" /> ></td>
      </tr>
      <tr>
            <td>How much do you want to save each year? </td>
            <td><input name="contribution" type="number" pattern="\d*" placeholder="An optional amount" size="9" value="<?php echo empty($_POST['contribution'])?0:$_POST['contribution']?>" /></td>
      </tr>
      <tr>
            <td>What Interest Rate do you receive (%)?</td>
            <td align="left" valign="top"><input name="ROI" type="number" pattern="\d*" placeholder="An interest rate"size="9" value="<?php echo @$_POST['ROI']?>" /></td>
      </tr>
      <tr>
            <td>How many years are you saving for?</td>
            <td align="left" valign="top"><input name="period" type="number" pattern="\d*" placeholder="How many years?" size="9" value="<?php echo @$_POST['period']?>" /></td>
      </tr> 
      <tr>
            <td>Preferred Currency?</td>
            <td align="left">

                <select name="currency" value=" <?php echo @$_POST['currency']?>" >
                      <option value="">Select...</option>
                      <option value="">None</option>
                      <option value=">&pound">&pound</option>
                      <option value="$" >$</option>
                      <option value="€">&euro</option>
                    <option value="¥">&yen</option>
                </select>
            </td>

        <tr>
                <td> </td>
                <td><input type="submit" value="Calculate" onclick="window.location='#results';"/></td>
        </tr>
       <tr>
                <td><input type="hidden" name="ok" value="1" /></td>
                <td> </td>
       </tr>

   
      </form>
</table>


</fieldset>
<fieldset>
    <legend id="results">My Results</legend>

    <script src="/Templates/hootLoot/javascript/showHide.js" type="text/javascript"></script>
    <script type="text/javascript">

        $(document).ready(function(){


           $('.show_hide').showHide({            
                speed: 500,  // speed you want the toggle to happen    
                easing: '',  // the animation effect you want. Remove this line if you dont want an effect and if you haven't included jQuery UI
                changeText: 1, // if you dont want the button text to change, set this to 0
                showText: 'Show me',// the button text to show when a div is closed
                hideText: 'Hide!' // the button text to show when a div is open
                             
            }); 

        });

</script>

    <div class="grid-container"> 
    <div class="hide-on-mobile grid-100 grid-parent">

<p>Would you like to see the calculations?       <a href="#" class="show_hide" rel="#slidingDiv"> Show Me</span></p>   </a>    

        <div id="slidingDiv" style="display:none";>
    <?php if(!empty($_POST['ok'])):
        $current_year=date("Y");
        $total_contribution=0;
        
        // balance before adding anything
        $balance=$_POST['invested_amount'];  
        $new_balance=$balance;      
        $total_interest=0;      
        $total_cash=0;
        $roi=0;?>
        
        <p> </p><table id="calcs_table" class='ccalc_table ccalc_result'>
      
      <tr><th>Year</th><th>Balance at <br>the start</th><th>Money <br>Added</th><th>Interest <br>Earned</th><th>Balance at <br>the end</th>
      <th>% Total <br>Return</th></tr><tbody>


  <?php for($i=0;$i<$_POST['period'];$i++):       
          $year=$current_year+$i;
 
         // add contribution
         $total_contribution+=$_POST['contribution'];
         
         // interest in $ for the period
         $interest=$new_balance*($_POST['ROI']/100);
         $total_interest+=$interest;                                                                  
         
         // now new balance
          $new_balance=$new_balance+$interest-$cash+$_POST['contribution'];;
          $old_balance=$new_balance-$interest-$cash-$_POST['contribution'];;     

          $principal=$new_balance;

          // total return at this point
          $roi=round(((($new_balance+$total_cash)/($balance+$total_contribution))-1)*100);

     
        for ($i = 0; $i <= $_POST['period']; $i++) {
            echo "This count is: $i";
            echo "['" . $year . "'," . $principal . "],<br>";
        } 




        ?>    

    <!--Google Chart - https://developers.google.com/chart/interactive/docs/gallery/linechart-->
<script type="text/javascript"
          src="https://www.google.com/jsapi?autoload={
            'modules':[{
              'name':'visualization',
              'version':'1',
              'packages':['corechart']
            }]
          }"></script>

    <script type="text/javascript">
      google.setOnLoadCallback(drawChart);

      function drawChart() {
                var data = new google.visualization.DataTable();
                    data.addColumn('string', 'Year');
                    data.addColumn('number', 'Balance');

         //       for($i=0;$i<$_POST['period'];$i++){ 
         //          data.addRows([
         //         echo "['" . $year . "'," . $balance . "],"; 
         //         ]);
         //      }
               

              for($i = 0; $i <= <?php echo @$_POST['period']?> ; $i++) {
                    data.addRows([
                      <?php
                         echo "['" . $year . "'," . $balance . "],";
                       ?>
                    ]);
                }                               

                var options = {
                  title: 'My Savings',
                  curveType: 'function',
                  legend: { position: 'bottom' } 
                };

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

    <!-- Create Table output-->
         

     <tr><td><?php echo $year?></td>
     <td><?php echo @$_POST['currency']?><?php echo number_format($old_balance)?></td> 
     <td><?php echo @$_POST['currency']?><?php echo number_format($_POST['contribution'])?></td>
     <td><?php echo @$_POST['currency']?><?php echo number_format($interest)?></td>
     <td><?php echo @$_POST['currency']?><?php echo number_format($new_balance)?></td>
     <td><?php echo number_format($roi)?>%</td></tr>         
    <?php endfor;?>   

    </tbody><tr><th>Total:</td><th></td>
    <th><?php echo @$_POST['currency']?><?php echo number_format($total_contribution)?></th>
    <th><?php echo @$_POST['currency']?><?php echo number_format($total_interest)?></th>
    <th><?php echo @$_POST['currency']?><?php echo number_format($new_balance);?></th>
    <th><?php echo number_format($roi)?>%</th></tr>
    </table>    
<?php endif; ?>
                                                                                                             
    <!-- Error messages-->
  <script type="text/javascript">
  function validateInvCalc(frm)
  {
      if(frm.invested_amount.value=="" || isNaN(frm.invested_amount.value))
      {
          alert("Please enter the amount of savings you currently have");
          frm.invested_amount.focus();
          return false;
      }
      
      if(frm.period.value=="")
      {
          alert("Please select number of years");
          frm.period.focus();
          return false;
      }
      
      if(frm.ROI.value=="" || isNaN(frm.ROI.value))
      {
          alert("Please enter the interest rate you will receive on your investment");
          frm.ROI.focus();
          return false;
      }
  }
  </script>
</div>              
</div>   
</div>
<br>
<!-- Results table-->    
      <table>
              <th>Your Results</th>                                    <th> </th><th> </th>
              <tr>
                  <td>You started off with:           </td>
                  <td align="left"><?php echo @$_POST['currency']?><?php echo number_format($balance)?>             </td>
                  <td>     </td>
              </tr>
              <tr>
                  <td>You saved:        </td>
                  <td align="left"><?php echo @$_POST['currency']?><?php echo number_format($total_contribution)?>           </td>
                    <td>&nbsp</td>
              </tr>                    
              <tr>
                  <td>You have earned interest of:           </td>
                  <td align="left"><?php echo @$_POST['currency']?><?php echo number_format($total_interest)?>            </td>
                  <td>&nbsp</td>
              </tr>                            
              <tr>
                  <td>At the end you will have:            </td>
                  <td align="left"><?php echo @$_POST['currency']?><?php echo number_format($new_balance)?>            </td>
                  <td>&nbsp</td>
              </tr>
      </table>

  
       <br>
       <br>
       <div class="grid-container"> 
          <div class="grid-33 tablet-grid-33 grid-parent">&nbsp</div>
          <div class="grid-66 tablet-grid-66 grid-parent">

              <input type="submit" value="Start Again" onclick="window.location='#start';"/>
          </div>
      </div>


    
<!-- Chart Output-->

          <div class="grid-container"> 
              <div class="grid-100 grid-parent">
                  <div id="curve_chart" style="width: 100%; height: auto"></div>
               </div>   
          </div>








</fieldset>

Edited by Ambienz
Link to comment
Share on other sites

When you write to your JS in PHP (on the server) you write whatever is in $year and $balance at the time. Later (on the client) the JS loops using those single values. You need an array of years and values.

 

I would use AJAX from your JS to get a JSON array and then use that for the chart.

 

BTW, I am getting many errors flagged regarding incorrect nesting of tags EG

 

<p>Would you like to see the calculations?       <a href="#" class="show_hide" rel="#slidingDiv"> Show Me</span></p>   </a>

Link to comment
Share on other sites

Thank you for taking the time to look at this Barand.

 

Unfortunately this is well beyond my level of knowledge and skill. Do you know where I could find this explained with an example?

 

Thanks for noting the errors.... poor recycling of code and Sublime doesn't show them to me.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.