jQuery + PHP HighChart未正确更新


jQuery + PHP HighChart not updating correctly

希望有人能提供帮助。我有一个jQuery图表(使用HighCharts),我使用PHP用数据填充它,我最初提取了30条记录,效果很好。然后,我希望每秒添加最新记录,因此我设置了setInterval选项。虽然这似乎有效,但最新记录没有添加,但每秒添加加载图表时的最后一条记录,使我相信 PHP 没有"刷新"。

这可能是显而易见的事情,我可能花了太多时间看它,完全错过了重点。

<script>
$('#graph-visual').highcharts({
    chart : {
        backgroundColor: "#FFFFF0",
        type: 'line',
        events : {
            load : function () {
                // set up the updating of the chart each second
                var series = this.series[0];
                setInterval(function () {

                    <?php
                        // Get Last entry only
                        include "db-conn.php";
                        $query =  "SELECT * FROM `cl50-iotdb`.`temperature_values` ";
                        $query .= "WHERE time_added IN (select max(time_added) from temperature_values GROUP BY entry_id)";
                        $query .= " ORDER BY time_added DESC LIMIT 1;";
                        $select_latest_temperature = mysqli_query($connection, $query);

                        if(!$select_latest_temperature)
                        {
                            echo "DB Connection Error";
                            die();
                        }

                        // Clear Var to ensure fresh data
                        unset($latest_temp);
                        while($row = mysqli_fetch_assoc($select_latest_temperature))
                        {
                            $latest_temp = $row['temperature'];
                        } 
                    ?>
                    series.addPoint([<?php echo $latest_temp?>]);
                }, 1000);
            }
        }
    },
    title : {
        text : 'Latest Temperature Readings'
    },
    yAxis: {
        title: {
           text: 'Temperature (°C)'
        }
    },
    exporting: {
        enabled: false
    },
    series : [{
        name : 'Arduino Data',
        data : (function () {

                <?php
                // Get last 30 entries
                include "db-conn.php";
                $query =  "SELECT temperature, time_added FROM `cl50-iotdb`.`temperature_values` ";
                $query .= "WHERE time_added IN (select max(time_added) from temperature_values GROUP BY entry_id)";
                $query .= " ORDER BY time_added DESC LIMIT 30;";
                $select_temperature = mysqli_query($connection, $query);
                if(!$select_temperature)
                {
                    echo "DB Connection Error";
                    die();
                }
                // Clear Arrays to ensure fresh data
                unset($temperatureArray);
                while($row = mysqli_fetch_array($select_temperature))
                {
                    $temperatureArray[] = $row['temperature'];
                } 
                ?>
                var data = [
                            <?php 
                                foreach (array_reverse($temperatureArray) as $temp)
                                {
                                    echo $temp . ", "; 
                                } 
                            ?>
                           ]
            return data;
        }())
    }]

});
</script>

提前感谢!

好的,正如 Larry 在评论中建议的那样,解决方案是使用 AJAX。为了将来参考,为了使它正常工作,我更改了以下内容:

图表元素被更改为使用称为PHP的AJAX,

chart : {
        backgroundColor: "#FFFFF0",
        type: 'line',
        events : {
            load : function () {
                // set up the updating of the chart each second
                var series = this.series[0];
                setInterval(function () 
                    {
                        $.ajax(
                            {  
                            type: "GET",
                            url: 'includes/get-latest-temp-graph.php',
                            success: function(NewTemp) 
                            {
                                series.addPoint([NewTemp],true, true);
                            },
                            cache: false
                        });
                    }, 2000);
            }
        }
    },

并且最初在图表元素中的 PHP 被移动到它自己的文件中,

<?php
// Set the JSON header
header("Content-type: text/json");
// Get Last entry only
include "db-conn.php";
$query =  "SELECT * FROM `cl50-iotdb`.`temperature_values` ";
$query .= "WHERE time_added IN (select max(time_added) from temperature_values GROUP BY entry_id)";
$query .= " ORDER BY time_added DESC LIMIT 1;";
$select_latest_temperature = mysqli_query($connection, $query);

if(!$select_latest_temperature)
{
    echo "DB Connection Error";
    die();
}

// Clear Var to ensure fresh data
unset($latest_temp);
while($row = mysqli_fetch_assoc($select_latest_temperature))
{
    $latest_temp = $row['temperature'];
} 
echo $latest_temp;
?>

上述两个更改解决了该问题,现在它根据数据库中的新数据每两秒自动更新一次。非常好!

我重新安排了您的代码,以使图表的所有呈现都是 ajax 调用的结果,并从您的 JavaScript 代码中删除 php。答案中的代码效果很好。如果您想要一种更分离的关注点的方法,请尝试一下我的解决方案。

索引.php文件:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>High Charts with Database</title>
    </head>
    <body>

         <!--high charts data-->
        <div id="graph-visual"></div>

<script src="https://code.jquery.com/jquery-2.2.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="js/services/tempchart.js"></script>     

</body>
</html>

JavaScript Service(file path js/services/tempservice.js):

(function($){
    //call the tempService
    TempService();

   function TempService(){//begin temp service

            $.ajax(
                    {
                        type: "GET",
                        url: 'services/firsttemps.php',
                        success: function (data)
                        {

                            //split data returned into an array of strings
                            var firstTemps = data.split(",");
                            //convert firstTemps to numbers
                            for (var i = 0; i < firstTemps.length; i++) {
                                //convert each string to number using the + operator
                                firstTemps[i] = +firstTemps[i];
                            }
                            //create new chart object
                            var chart = new Highcharts.Chart({
                                chart: {
                                    backgroundColor: "#FFFFF0",
                                    type: 'line',
                                    renderTo: "graph-visual"
                                 },
                                title: {
                                    text: 'Latest Temperature Readings'
                                },
                                yAxis: {
                                    title: {
                                        text: 'Temperature (°C)'
                                    }
                                },
                                exporting: {
                                    enabled: false
                                },
                                series: {
                                    name: "Arduino Data",
                                    data: []
                                }
                            });

                            chart.addSeries({
                                name: "Arduino Data",
                                data: firstTemps
                            });

                            window.setInterval(function ()
                            {
                                $.ajax(
                                        {
                                            type: "GET",
                                            url: 'services/latesttemp.php',
                                            success: function (latest)
                                            {
                                                //add the lastest temp to the chart
                                                chart.series[0].addPoint([latest],true,true);
                                            },
                                            cache: false
                                        });
                            }, 2000);

                        },
                        cache: false
                    });

   }//end temp service
})(jQuery);

名为服务的文件夹中的 PHP 文件:

第一临时.php

        <?php
        // Get last 30 entries
        include "db-conn.php";
        $query =  "SELECT temperature, time_added FROM `cl50-iotdb`.`temperature_values` ";
        $query .= "WHERE time_added IN (select max(time_added) from temperature_values GROUP BY entry_id)";
        $query .= " ORDER BY time_added DESC LIMIT 30;";
        $select_temperature = mysqli_query($connection, $query);
        if(!$select_temperature)
        {
            echo "DB Connection Error";
            die();
        }
        // Clear Arrays to ensure fresh data
        unset($temperatureArray);
        while($row = mysqli_fetch_array($select_temperature))
        {
            $temperatureArray[] = $row['temperature'];
        } 

        //echo data for the ajax call
        echo implode(",",$temperatureArray);

       ?>

最新温度.php

<?php
// Set the JSON header
header("Content-type: text/json");
// Get Last entry only
include "db-conn.php";
$query =  "SELECT * FROM `cl50-iotdb`.`temperature_values` ";
$query .= "WHERE time_added IN (select max(time_added) from temperature_values GROUP BY entry_id)";
$query .= " ORDER BY time_added DESC LIMIT 1;";
$select_latest_temperature = mysqli_query($connection, $query);

if(!$select_latest_temperature)
{
    echo "DB Connection Error";
    die();
}

// Clear Var to ensure fresh data
unset($latest_temp);
while($row = mysqli_fetch_assoc($select_latest_temperature))
{
    $latest_temp = $row['temperature'];
} 
echo $latest_temp;

?>

db-conn.php

<?php
//replace with the appropriate values if necessary
$connection = new mysqli("localhost", "user", "password", "cl50-iotdb");
//catch errors
if ($connection->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}