简体   繁体   中英

Google Chart with dynamic data and pagination is it possible?

I want to use a Google Chart on my marketing project. I want to display a Google Donut Chart with AJAX pagination.

The problem is when I go to the next page, the Google Chart wont show/display/load. It only shows data in the first load. Here is my sample code below:

index.php

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.12.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("#results" ).load("fetch_pages.php"); //load initial records
    //executes code below when user click on pagination links
    $("#results").on( "click", ".pagination a", function (e){   
        e.preventDefault();
        $(".loading-div").show(); //show loading element
        var page = $(this).attr("data-page"); //get page number from link
        $("#results").load("fetch_pages.php",{"page":page}, function(){//get content from PHP page
            $(".loading-div").hide(); //once done, hide loading element

        });
    });

});

</script>

<div class="loading-div"><img src="ajax-loader.gif" ></div>
<div id="results"><!-- content will be loaded here --></div>

fetch_pages.php

<?php
/* Title : Ajax Pagination with jQuery & PHP
Example URL : http://www.sanwebe.com/2013/03/ajax-pagination-with-jquery-php */

//continue only if $_POST is set and it is a Ajax request
if(isset($_POST) && isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){

    include("config.inc.php");  //include config file
    //Get page number from Ajax POST
    if(isset($_POST["page"])){
        $page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH); //filter number
        if(!is_numeric($page_number)){die('Invalid page number!');} //incase of invalid page number
    }else{
        $page_number = 1; //if there's no page number, set it to 1
    }

    //get total number of records from database for pagination
    $results = $mysqli->query("SELECT COUNT(DISTINCT goals_date) FROM wp_daily_goals WHERE user_ID = '$loguser'");
    $get_total_rows = $results->fetch_row(); //hold total records in variable
    //break records into pages
    $total_pages = ceil($get_total_rows[0]/$item_per_page);

    //get starting position to fetch the records
    $page_position = (($page_number-1) * $item_per_page);


    //Limit our results within a specified range. 
    $results = $mysqli->prepare("SELECT user_ID, goals_date, TIME_FORMAT(SEC_TO_TIME(SUM(TIME_TO_SEC(total_time))), '%H:%i') AS st_time, SUM(twcm) AS stwcm, SUM(slas) AS sslas, SUM(bas) AS sbas, SUM(iph) AS siph, SUM(ias) AS sias, 
SUM(IF(lead_type = 'expireds', twcm + slas + bas + iph + ias, 0)) AS 'expireds', 
SUM(IF(lead_type = 'fsbos', twcm + slas + bas + iph + ias, 0)) AS 'fsbos', 
SUM(IF(lead_type = 'followup', twcm + slas + bas + iph + ias, 0)) AS 'followup', 
SUM(IF(lead_type = 'buyers', twcm + slas + bas + iph + ias, 0)) AS 'buyers', 
SUM(IF(lead_type = 'agents', twcm + slas + bas + iph + ias, 0)) AS 'agents', 
SUM(IF(lead_type = 'circlemarketing', twcm + slas + bas + iph + ias, 0)) AS 'circlemarketing', 
SUM(IF(lead_type = 'doorknocking', twcm + slas + bas + iph + ias, 0)) AS 'doorknocking', 
SUM(IF(lead_type = 'investor', twcm + slas + bas + iph + ias, 0)) AS 'investors'
FROM wp_daily_goals WHERE user_ID = '$loguser' GROUP BY goals_date ORDER BY goals_date ASC LIMIT $page_position, $item_per_page");
    $results->execute(); //Execute prepared Query
    $results->bind_result($user_ID, $goals_date, $st_time, $stwcm, $sslas, $sbas, $siph, $sias, $expireds, $fsbos, $followup, $buyers, $agents, $circlemarketing, $doorknocking, $investors); //bind variables to prepared statement

    //Display records fetched from database.
    echo '
    <script type="text/javascript">
      google.charts.load("current", {packages:["corechart"]});
      google.charts.setOnLoadCallback(drawChart);
      function drawChart() {';
    while($results->fetch()){ //fetch values google donutchart
        echo '$(document).ready(function(){
            var data = google.visualization.arrayToDataTable([ 
          ["Task", "Hours per Day"],
          ["Expired - '.$expireds.'",     '.$expireds.'],
          ["FSBOs - '.$fsbos.'",      '.$fsbos.'],
          ["Follow Up - '.$followup.'",  '.$followup.'],
          ["Buyers - '.$buyers.'", '.$buyers.'],
          ["Agent - '.$agents.'",    '.$agents.'],
          ["Circle Marketing - '.$circlemarketing.'",    '.$circlemarketing.'],
          ["Door Knocking - '.$doorknocking.'",    '.$doorknocking.'],
          ["Investor - '.$investors.'",    '.$investors.']
        ]);

        var options = {
          title: "My Daily Goals",
          pieHole: 0.4,
          width: 400, height: 250,
        chartArea: {width: "95%", height: "95%"},
        legend: {"position":"right","alignment":"center"},
      };

      var chart = new google.visualization.PieChart(document.getElementById("donutchart"));
      chart.draw(data, options);
        })';}
    echo '};
    </script>
    <div id="donutchart"></div>
    ';

    echo '<div align="center">';
    /* We call the pagination function here to generate Pagination link for us. 
    As you can see I have passed several parameters to the function. */
    echo paginate_function($item_per_page, $page_number, $get_total_rows[0], $total_pages);
    echo '</div>';

    exit;
}
################ pagination function #########################################
function paginate_function($item_per_page, $current_page, $total_records, $total_pages)
{
    $pagination = '';
    if($total_pages > 0 && $total_pages != 1 && $current_page <= $total_pages){ //verify total pages and current page number
        $pagination .= '<ul class="pagination">';

        $right_links    = $current_page + 3; 
        $previous       = $current_page - 3; //previous link 
        $next           = $current_page + 1; //next link
        $first_link     = true; //boolean var to decide our first link

        if($current_page > 1){
            $previous_link = ($previous==0)? 1: $previous;
            $pagination .= '<li class="first"><a href="#" data-page="1" title="First">&laquo;</a></li>'; //first link
            $pagination .= '<li><a href="#" data-page="'.$previous_link.'" title="Previous">&lt;</a></li>'; //previous link
                for($i = ($current_page-2); $i < $current_page; $i++){ //Create left-hand side links
                    if($i > 0){
                        $pagination .= '<li><a href="#" data-page="'.$i.'" title="Page'.$i.'">'.$i.'</a></li>';
                    }
                }   
            $first_link = false; //set first link to false
        }

        if($first_link){ //if current active page is first link
            $pagination .= '<li class="first active">'.$current_page.'</li>';
        }elseif($current_page == $total_pages){ //if it's the last active link
            $pagination .= '<li class="last active">'.$current_page.'</li>';
        }else{ //regular current link
            $pagination .= '<li class="active">'.$current_page.'</li>';
        }

        for($i = $current_page+1; $i < $right_links ; $i++){ //create right-hand side links
            if($i<=$total_pages){
                $pagination .= '<li><a href="#" data-page="'.$i.'" title="Page '.$i.'">'.$i.'</a></li>';
            }
        }
        if($current_page < $total_pages){ 
                $next_link = ($i > $total_pages) ? $total_pages : $i;
                $pagination .= '<li><a href="#" data-page="'.$next_link.'" title="Next" class="next">&gt;</a></li>'; //next link
                $pagination .= '<li class="last"><a href="#" data-page="'.$total_pages.'" title="Last">&raquo;</a></li>'; //last link
        }

        $pagination .= '</ul>'; 
    }
    return $pagination; //return pagination links
}

?>

There are many options but i like to load graph using ajax. Because in this want it will make your page fast as you can enjoy parallel computing in this way. This is just for idea. you can get "data rows" from server and then fill those data rows.

$.ajax({
url: '/your server.php'
    , type: "POST"
    //, contentType: 'application/json; charset=utf-8'
    , async: true
    //, cache: true
    //, timeout: 10000
    , success: function (ServerSideData) {

        google.charts.load('current', { packages: ['corechart', 'controls'] });
        google.charts.setOnLoadCallback(function () {
            drawChartRangeFilter(dataRows);
        });

    }
});

function drawChartRangeFilter(dataRows){

    var options2 = {
        title: 'Daily view ',
        vAxis: {
            //title: 'Sales / Forecast',
            viewWindow: {
                min: 0,
                max: maxScaleValue
            }
        },
        hAxis: { title: 'Days' },
        seriesType: 'bars',
        series: { 1: { type: 'line' } },
        legend: { position: "bottom" },
        chartArea: {
            left: '10%',
            top: '5%',
            width: '88%',
            height: '80%'
        },
        tooltip: { isHtml: true },
        pointSize: 5,
        pointShape: 'square'
    };

 var data = new google.visualization.DataTable();
    data.addColumn('string', 'Month');
    data.addColumn('string', 'Day');
    data.addColumn('number', 'Sales');
    data.addColumn({ type: 'string', role: 'tooltip', 'p': { 'html': true } });
    data.addColumn('number', 'Forecast');
    data.addColumn({ type: 'string', role: 'tooltip', 'p': { 'html': true } });

    data.addRows(dataRows);

    var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
    chart.draw(data, options2);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM