Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a date range variable dynamically and redraw a Google chart?

I am using PHP to set a date range for creating a Google Line Chart. For each date in the range a variable is set ($running_balance) to create the points on the line chart using data in a database. I would like to be able to set the variable $end, which essentially determines the date range, dynamically, but I am not sure how to do this so that the chart would be redrawn according to this new range. I am aware that I could create a new function that includes drawChart(); to redraw the chart, and I would be using three buttons to either set the date range to 1 year, 3 months, or 1 month, but I am not sure how to put all this together. Here is the code that I currently have:

$begin = new DateTime(date('Y-m-d', strtotime('+1 days')));
$end = new DateTime(date('Y-m-d', strtotime('+365 days')));
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);

foreach ( $period as $dt ) {

$date_display = $dt->format("D j M");

.....  code to generate $running_balance .....

$temp = array();

    $temp[] = array('v' => (string) $date_display); 
    $temp[] = array('v' => (string) $running_balance);
    $temp[] = array('v' => (string) $running_balance);
    $rows[] = array('c' => $temp);
}

$table['rows'] = $rows;
$jsonTable = json_encode($table);

<script type="text/javascript">

    // Load the Visualization API and the piechart package.
    google.load('visualization', '1', {'packages':['corechart']});

    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawChart);

    var table = <?php echo $jsonTable; ?>;

    function drawChart() {
    var data = new google.visualization.DataTable(table);

      // Create our data table out of JSON data loaded from server.
        //  var data = new google.visualization.DataTable(<?=$jsonTable?>);
      var formatter = new google.visualization.NumberFormat({fractionDigits:2,prefix:'\u00A3'});
      formatter.format(data, 1);
      var options = {
          pointSize: 5,
          legend: 'none',
          hAxis: { showTextEvery:31 },
          series: {0:{color:'2E838F',lineWidth:2}},
          chartArea: {left:50,width:"95%",height:"80%"},
          backgroundColor: '#F7FBFC',
          height: 400
        };
      // Instantiate and draw our chart, passing in some options.
      //do not forget to check ur div ID
      var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }

</script>
like image 304
Nick Avatar asked Apr 07 '13 22:04

Nick


1 Answers

OK, if I'm understanding you correctly, you're having trouble conceiving and designing what parts of these actions are server-side (PHP) and what parts are client side (Javascript) and then the client-server communication strategy. This is a common speedbump. There's several ways to deal with it.

First (and less preferred) you could create a form and reload the whole page with the new date range:

// we're looking for '+1 year', '+3 months' or '+1 month'. if someone really
// wants to send another value here, it's not likely to be a security risk
// but know your own application and note that you might want to validate
$range = isset($_GET['range'])&&$_GET['range']?$_GET['range']:'+1 year';

$begin = new DateTime(date('Y-m-d', strtotime('+1 days')));
$end = new DateTime(date('Y-m-d', strtotime($range)));
// ... the rest of your code to build the chart.
?>
<form action="<?= $_SERVER['PHP_SELF']; ?>" method="get">
    <select name="range" size="1">
        <option value="+1 year">1 year</option>
        <option value="+3 months">3 months</option>
        <option value="+1 month">1 month</option>
    </select>
    <input type="submit" name="action" value="Redraw Chart">
</form>

... the reason that's the less preferred is because it causes a whole refresh of the page.

If you want to avoid a whole page refresh, you're doing pretty much the same thing, but do it with ajax. The setup is almost identical, just a couple minor changes:

// between building the data table and the javascript to build the chart...
$jsonTable = json_encode($table);
if (isset($_GET['ajax']) && $_GET['ajax']) {
    echo json_encode(array('table' => $table));
    exit;
}
// remainder of your code, then our new form from above
?>
<form id="redraw_chart_form" action="<?= $_SERVER['PHP_SELF']; ?>" data-ajaxaction="forecast.php" method="get">
    <? foreach ($_GET as $key => $val) { ?>
    <input type="hidden" name="<?= $key; ?>" value="<?= $val; ?>">
    <? } ?>
    <input type="hidden" name="ajax" id="redraw_chart_form_ajax" value="0">
    <select name="range" size="1">
        <option value="+1 year">1 year</option>
        <option value="+3 months">3 months</option>
        <option value="+1 month">1 month</option>
    </select>
    <input type="submit" name="action" value="Redraw Chart">
</form>
<script>
    // I'm assuming you've got jQuery installed, if not there are
    // endless tutorials on running your own ajax query
    $('#redraw_chart_form').submit(function(event) {
        event.preventDefault(); // this stops the form from processing normally
        $('#redraw_chart_form_ajax').val(1);
        $.ajax({
            url: $(this).attr('data-ajaxaction'),
            type: $(this).attr('method'),
            data: $(this).serialize(),
            complete: function() { $('#redraw_chart_form_ajax').val(0); },
            success: function(data) {
                // referring to the global table...
                table = data.table;
                drawChart();
            },
            error: function() {
                // left as an exercise for the reader, if ajax
                // fails, attempt to submit the form normally
                // with a full page refresh.
            }
        });
        return false; // if, for whatever reason, the preventDefault from above didn't prevent form processing, this will
    });
</script>

Edit for clarity:

  1. Don't forget to use the following block of code from the first (page refresh) example, otherwise you're not using the form at all:

    $range = isset($_GET['range'])&&$_GET['range']?$_GET['range']:'+1 year';

    $begin = new DateTime(date('Y-m-d', strtotime('+1 days')));

    $end = new DateTime(date('Y-m-d', strtotime($range)));

  2. Ajax will only work if the only data you're sending back is the json encoded block, which means your chart building data needs to be at the top of the script before any HTML output is started, including your page template. If you can't put the chart building code at the top of the script, then you'll have to add it to a whole separate script that all it does is calculate the data for the chart, and then you can have it return the ajax data without all of the other HTML on the page. If you can't do either of those things, you'll just have to turn off the Ajax bit and do a whole page refresh.


Edit 2: I added the data-ajaxaction attribute to the <form> element, this is a user defined attribute that I made up to provide a different action just for ajax. I also changed the $.ajax() call to use this attribute rather than the action attribute.

like image 87
Jason Avatar answered Nov 09 '22 23:11

Jason