jQuery + PHP HighChart无法正确更新

时间:2016-02-27 15:30:58

标签: javascript php jquery highcharts

希望有人可以提供帮助。我有一个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>

提前致谢!

2 个答案:

答案 0 :(得分:1)

好的,正如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;
?>

上述两个更改修复了问题,现在它会根据数据库中的新数据每两秒自动更新一次。优良!

答案 1 :(得分:0)

我做了一些重新安排你的代码,使你的图表的所有呈现都是ajax调用的结果,并从你的JavaScript代码中删除php。你的答案中的代码很有效。如果你想要一个更加分离的关注方法,那么试试我的解决方案。

index.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服务(文件路径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);

名为services的文件夹中的PHP文件:

firsttemps.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);


       ?>

latesttemp.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;
}