如何只刷新包含谷歌图表和PHP的div?

时间:2016-06-03 14:45:34

标签: javascript php html5 charts google-visualization

我有一个包含多个div的管理页面。而一些div包含谷歌图表。 我的图表来自php + MySQL数据。

一些div(或图表)更新60秒。一些div(或图表)将更新1小时。 所以不同的div应该更新不同的时期。 (这就是为什么我不刷新整页。

无论如何,当我刷新页面时没有问题,但当我尝试更新我的div时,div更新,但是图中没有任何内容。 你能救我吗?

这是我的PHP代码:

  // QUERY AND PHP ARRAY FOR JSON 
  $query = "SELECT CONCAT(cdate,' ',chour,':00:00') AS ctime ,sum(bytesin*0.000002222) as totalKbpsin, sum(bytesout*0.000002222) as totalKbpsout FROM traffic_user_daily group by cdate,chour HAVING ctime >= now() - INTERVAL 1 DAY ";

 $result = $conn->query($query);
 $rows= array();
 $table = array();
 $table['cols'] = array(
 array('label' => 'Tarih' , 'type' => 'string'),
 array('label' => 'Inbound' , 'type' => 'number'),
 array('label' => 'Outbound' , 'type' => 'number'),

 );
 foreach($result as $r) {
 $temp = array();
 $temp[] = array('v' => (string) substr($r['ctime'],11,5));
 $temp[] = array('v' => (int) $r['totalKbpsin']);
 $temp[] = array('v' => (int) $r['totalKbpsout']);
 $rows[] = array('c' => $temp);
 }
 $table['rows'] = $rows;
 $jsonTable = json_encode($table);
 ?>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

   <script type="text/javascript">
        // CHART JAVA CODE
        google.charts.load('visualization','current', {'packages':['corechart','bar'], 'language': 'en'});

        // Draw the line chart is loaded.
        google.setOnLoadCallback(drawBigChart);     


        // Callback that draws the line chart

        function drawBigChart() {            
                var data = new google.visualization.DataTable(<?=$jsonTable?>);

            var options = {

                chartArea: {
                    'height': '80%',
                    left: "5%" 
                },

                legend: {
                    position: 'right', 
                    textStyle: {
                        color: '#bdbdbd', 
                        fontSize: 12
                    }
                },

                hAxis: {
                    showTextEvery:2,
                    textStyle: {color: '#bdbdbd',
                    fontSize: 12,
                    },
                    baselineColor: '#bdbdbd',
                    gridlines: {color:'bdbdbd'},
                },


                vAxis: {
                    baselineColor: '#bdbdbd',
                    textStyle: {color:'#bdbdbd'},
                    gridlines: {color:'#bdbdbd' },
                    minValue: 0,
                },

                intervals: { 'style':'area' },
                curveType: 'function',
                crosshair: {orientation: 'vertical'},

                animation: {
                    startup: true,
                    duration: 1000
                },
            };

            var chart = new google.visualization.LineChart(document.getElementById('chart_div'));

            chart.draw(data, options);

        }

</script>
   <!-- OUTER DIV -->
                <div class="col s12 m12">
                  <!-- CHART DIV -->
                    <div id="dash_big_chart" class="card">
                        <div class="card-content">
                            <div>
                                <span class="card-title grey-text lighten-1">
    <?php echo $_SESSION['companyname'] ?></span></div>
    <div id="chart_div">
    </div></div></div></div>
    <script type="text/javascript">

    /// refresh script ////

    setInterval(function(){
      $("#dash_big_chart").load('big_chart.php')
      },60000);
    });

    </script>

然后我有另一个名为big_chart.php的php页面。它包含JSON部分的Query和数组,除了google.charts.load和CHAR DIV之外的Graph java。

你能帮我吗?

4 个答案:

答案 0 :(得分:0)

jQuery load()想要将HTML加载到页面元素中。

你想要做的是完全不同的: 你想通过ajax请求获取json数据,然后让googlecharts用新数据重绘图表。

您必须将json数据作为参数添加到drawBigChart函数中。

代码看起来像这样:

// For the first load you can pass the json data just like you did before.
google.setOnLoadCallback(function(){
    drawBigChart(<?=$jsonTable?>);
});

function drawBigChart(json_data) {
    // pass the parameter into the google charts DataTable
    var data = new google.visualization.DataTable(json_data);
    var options = {...}; // I left out the options here only to make the code more visible
    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(data, options);
}

// For the interval you retrieve the data via ajax request and pass
// it to the drawBigChart function
setInterval(function(){
    $.getJSON( "big_chart.php", function( data ) {
        drawBigChart(data);
    });
},60000);

答案 1 :(得分:0)

setInterval()中,您正在替换<div id="dash_big_chart"/>及其中的所有内容,包括<div id="chart_div"/>,这是Google绘制图表的区域。

然而,在JavaScript中,实际绘制图表的代码高于函数drawBigChart()。并且绘制到图表的数据是

var data = new google.visualization.DataTable(<?=$jsonTable?>);

要完成你想要的,你需要重构。 您不需要下载新的HTML,只需下载新数据并更新图表。

更改drawBigChart()方法以获取作为图表数据的参数,因此您可以将其称为drawBigChart(jsonTable)

一旦你可以这样做,而不是像现在一样加载HTML并替换div,你只需要加载新的JSON数据并用新数据调用drawBigChart(newJsonTable)

这样的东西
setInterval(function(){
  $.ajax({
    'url': 'get_new_data.php', // url should return only JSON data
    'dataType': 'json',
    'async': true
  }).success(function(result) {
    // Draw the chart again with the updated data
    drawBigChart(result);
  });
}, 60000); // 60 second refresh

答案 2 :(得分:0)

我按照你的描述更改了我的页面:

google.charts.load('visualization','current', {'packages':  ['corechart','bar'], 'language': 'en'});
google.setOnLoadCallback(drawBigChart);
        function drawBigChart(jsonTable) { 
           var data = new google.visualization.DataTable(<?=$jsonTable?>);

            var options = { some visual thing};
            var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
            chart.draw(data, options);
    }

和间隔脚本:

 $(document).ready(function(){
 $("#activeuserlist").on("click", "a.modal-trigger", function(){
 $('#modalkes').openModal();
});
setInterval(function(){
    $("#activeuserlist").load('activeuserlist2.php') //another DIV

    $("#dash_kullanicisayisi").load('kullanicisayisi.php') //ANother DIV

   $.ajax({
    'url': 'get_new_data.php', // url should return only JSON data
    'dataType': 'json',
    'async': true
    }).success(function(result) {
    // Draw the chart again with the updated data
   drawBigChart(result);
   });
   },60000);
 });

我的get_new_data.php是这样的:

   <?php
   require_once("inc/functions.php"); 
   startSession();
   connectDB($conn);

   date_default_timezone_set('Europe/Istanbul');
   mb_internal_encoding("UTF-8");

   $now = date("Y-m-d H:m:s");
   $query = "SELECT CONCAT(cdate,' ',chour,':00:00') AS ctime ,sum(bytesin*0.000002222) as totalKbpsin, sum(bytesout*0.000002222) as totalKbpsout FROM traffic_user_daily group by cdate,chour HAVING ctime >= now() - INTERVAL 1 DAY ";
   $result = $conn->query($query);

   $rows= array();
   $table = array();
   $table['cols'] = array(
   array('label' => 'Tarih' , 'type' => 'string'),
   array('label' => 'Inbound' , 'type' => 'number'),
   array('label' => 'Outbound' , 'type' => 'number'),

   );
   foreach($result as $r) {
   $temp = array();
   $temp[] = array('v' => (string) substr($r['ctime'],11,5));
   $temp[] = array('v' => (int) $r['totalKbpsin']);
   $temp[] = array('v' => (int) $r['totalKbpsout']);
   $rows[] = array('c' => $temp);
   }
   $table['rows'] = $rows;
   $jsonTable = json_encode($table);
   echo $jsonTable;
   ?>

当我浏览此页面时,我得到类似JSON数据的内容:

    {"cols":[{"label":"Tarih","type":"string"},{"label":"Inbound","type":"number"},{"label":"Outbound","type":"number"}],"rows":[{"c":[{"v":"14:00"},{"v":6213},{"v":891}]},{"c":[{"v":"15:00"},{"v":6914},{"v":915}]},{"c":[{"v":"16:00"},{"v":5645},{"v":1789}]},{"c":[{"v":"17:00"},{"v":5821},{"v":1771}]},{"c":[{"v":"18:00"},{"v":3242},{"v":1753}]},{"c":[{"v":"19:00"},{"v":7536},{"v":685}]},{"c":[{"v":"20:00"},{"v":6902},{"v":696}]},{"c":[{"v":"21:00"},{"v":7140},{"v":1184}]},{"c":[{"v":"22:00"},{"v":5971},{"v":502}]},{"c":[{"v":"23:00"},{"v":9506},{"v":1353}]},{"c":[{"v":"00:00"},{"v":8783},{"v":2855}]},{"c":[{"v":"01:00"},{"v":3125},{"v":1044}]},{"c":[{"v":"02:00"},{"v":2500},{"v":1858}]},{"c":[{"v":"03:00"},{"v":534},{"v":1721}]},{"c":[{"v":"04:00"},{"v":658},{"v":1940}]},{"c":[{"v":"05:00"},{"v":839},{"v":93}]},{"c":[{"v":"06:00"},{"v":1041},{"v":200}]},{"c":[{"v":"07:00"},{"v":1154},{"v":97}]},{"c":[{"v":"08:00"},{"v":2684},{"v":1467}]},{"c":[{"v":"09:00"},{"v":7297},{"v":2099}]},{"c":[{"v":"10:00"},{"v":4143},{"v":1244}]},{"c":[{"v":"11:00"},{"v":7645},{"v":1535}]},{"c":[{"v":"12:00"},{"v":4411},{"v":868}]},{"c":[{"v":"13:00"},{"v":5323},{"v":1119}]}]}

图形刷新为图像但不显示新值。 我从HTTPFOX检查get_new_data.php拉取正确的数据,图表刷新。但图表没有变化。还是一样的图。

答案 3 :(得分:0)

我想我解决了这个问题:

google.charts.load('visualization','current', {'packages':['corechart','bar'], 'language': 'en'});
google.setOnLoadCallback(drawBigChart);
function drawBigChart() {
        var jsonData = $.ajax({
            url: "get_new_data.php",
            dataType: "json",
            async: false
            }).responseText;

        var data = new google.visualization.DataTable(jsonData);
        var options = {something  for visualisation}
        var chart = new google.visualization.LineChart(document.getElementById('chart_div'));

        chart.draw(data, options);
        }

    $(document).ready(function(){
            $("#dash_kullanicisayisi").load('kullanicisayisi.php')
            $.ajax({
                'url': 'get_new_data.php', // url should return only JSON data
                'dataType': 'json',
                'async': true
            }).success(function(result) {
                //Draw the chart again with the updated data
                drawBigChart(result);
            });
        },60000);
    });

解决了我的问题。现在图表刷新并填充新数据。 感谢您的帮助。