带有MySQL数据的Highcharts动态图表不会重新加载

时间:2014-03-18 23:33:07

标签: javascript mysql charts highcharts

大家晚上好,

这一刻我尝试使用HighChart / HighStock,几周后我就可以在图表中显示我的MySQL数据了。但是:我总是想要更多。

好吧,我试着找到一个动态的图表,这个图表就像你可能从网站上知道的例子一样令人耳目一新。 http://jsfiddle.net/sdorzak/HsWF2/

我使用示例代码作为指南。它不起作用,但认为问题是缺少y轴,因为y轴数据来自我的MySQL数据库,而x轴应该是当前时间。

  <!DOCTYPE HTML>
  <html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>POS RESULT</title>

    <script type="text/javascript"   src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script src="http://code.highcharts.com/highcharts.js"></script>
    <script src="http://code.highcharts.com/modules/exporting.js"></script>

</head>

        <body>

    <?php
include "config.php";

$SQL1 =     "SELECT * FROM Prices WHERE ticker ='FB'";

$result1 = mysql_query($SQL1);
$data1 = array();
while ($row = mysql_fetch_array($result1)) {
   $data1[] = $row['Close'];
}


?>

<script type="text/javascript">
$(function () {
    var chart;
    $(document).ready(function() {
        chart = new Highcharts.Chart({
            chart: {
                renderTo: 'container',
                type: 'line',
                marginRight: 130,
                marginBottom: 25,
                events: {
                  load: function() 
                  {

                     var series = this.series[0];
                     setInterval(function() {
                     var x = (new Date()).getTime();
                     series.addPoint([x], true);
                  }, 1000);
            },
            title: {
                text: 'Monthly Average Temperature',
                x: -20 //center
            },
            subtitle: {
                text: 'Source: WorldClimate.com',
                x: -20
            },
            xAxis: {
                                type: 'datetime',
                tickPixelInterval: 150

                //categories: [<?php echo join(',', $data2); ?>],
            },
            yAxis: {
                title: {
                    text: 'Temperature (°C)'
                },
                plotLines: [{
                    value: 0,
                    width: 1,
                    color: '#808080'
                }]
            },
            tooltip: {
                formatter: function() {
                        return '<b>'+ this.series.name +'</b><br/>'+
                        this.x +': '+ this.y +'°C';
                }
            },
            legend: {
                layout: 'vertical',
                align: 'right',
                verticalAlign: 'top',
                x: -10,
                y: 100,
                borderWidth: 0
            },
            series: [{
                name: 'Tokyo',
                data: [<?php echo join(',', $data1);  ?>]
            }]
        });
    });

});
    </script>

<div id="container" style="min-width: 500px; height: 400px; margin: 0 auto"></div>

</body>
   </html>

我正在谈论的这段文字以及样本中显示的内容是

    chart: {
        renderTo: 'container',
        type: 'spline',
        marginRight: 10,
        events: {
            load: function() {

                // set up the updating of the chart each second
                var series = this.series[0];
                setInterval(function() {
                    var x = (new Date()).getTime(), // current time
                        y = Math.random();
                    series.addPoint([x, y], true, true);
                }, 1000);
            }
        }

但是,正如我已经写过的那样,我不需要一个随机的y轴,只需要x轴。

也许你可以提供帮助。 谢谢你的帮助。

编辑: 活服务器data.php

<?php
// Set the JSON header
header("Content-type: text/json");


include "config.php";

$SQL1 =     "SELECT * FROM Prices WHERE Ticker ='TSLA'";

$result1 = mysql_query($SQL1);

while ($row = mysql_fetch_array($result1)) {
   $data1[] = $row['Close'];
}

// The x value is the current JavaScript time, which is the Unix time multiplied 
// by 1000.
$x = time() * 1000;
// The y value is a random number
$y = $data1;

// Create a PHP array and echo it as JSON
$ret = array($x, $y);
echo json_encode($ret);
?>

值“关闭”是十进制24,4。

2 个答案:

答案 0 :(得分:0)

查看该解决方案:http://www.highcharts.com/studies/live-server.htm

    var chart; // global

    /**
     * Request data from the server, add it to the graph and set a timeout to request again
     */
    function requestData() {
        $.ajax({
            url: 'live-server-data.php', 
            success: function(point) {
                var series = chart.series[0],
                    shift = series.data.length > 20; // shift if the series is longer than 20

                // add the point
                chart.series[0].addPoint(eval(point), true, shift);

                // call it again after one second
                setTimeout(requestData, 1000);  
            },
            cache: false
        });
    }

    $(document).ready(function() {
        chart = new Highcharts.Chart({
            chart: {
                renderTo: 'container',
                defaultSeriesType: 'spline',
                events: {
                    load: requestData
                }
            },
            title: {
                text: 'Live random data'
            },
            xAxis: {
                type: 'datetime',
                tickPixelInterval: 150,
                maxZoom: 20 * 1000
            },
            yAxis: {
                minPadding: 0.2,
                maxPadding: 0.2,
                title: {
                    text: 'Value',
                    margin: 80
                }
            },
            series: [{
                name: 'Random data',
                data: []
            }]
        });     
    });

答案 1 :(得分:0)

我试图创建另一个与我的条形图相关的页面。你可以浏览他的代码。它对我有用

<!DOCTYPE html>
<html>
   <head>
      <?php
         session_start();


         ?>
      <meta charset="utf-8">
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
      <script src="http://code.highcharts.com/highcharts.js"></script>
      <script src="http://code.highcharts.com/modules/exporting.js"></script>
      <script>
         $('#calendar').datepicker({
         });

         !function ($) {
           $(document).on("click","ul.nav li.parent > a > span.icon", function(){          
             $(this).find('em:first').toggleClass("glyphicon-minus");      
           }); 
           $(".sidebar span.icon").find('em:first').addClass("glyphicon-plus");
         }(window.jQuery);

         $(window).on('resize', function () {
           if ($(window).width() > 768) $('#sidebar-collapse').collapse('show')
         })
         $(window).on('resize', function () {
           if ($(window).width() <= 767) $('#sidebar-collapse').collapse('hide')
         })
      </script> 
      <style>
         .selection{
         border: 1px solid gray;
         border-radius: 10px;
         padding: 10px;
         text-decoration:none;
         float:left;
         margin:4px;
         text-align:center;
         display: block;
         color: green;
         }
         .page-header{
         text-align:center;
         text-decoration:hover;
         color: blue;
         font-size: 30px;
         }
      </style>
      <script>
         $(function () {

             //on page load  
             getAjaxData(1);

             //on changing select option
             $('#dynamic_data').change(function(){
               var val = $('#dynamic_data').val();
               getAjaxData(val);
             });

             function getAjaxData(id){

             //use getJSON to get the dynamic data via AJAX call
             $.getJSON('datab1.php', {id: id}, function(chartData) {
               $('#container').highcharts({
                 chart: {
                   type: 'column'
                 },
                 title: {
                   text: 'Analysis of Data Type in The World'
                 },
                 xAxis: {
                 categories: ['Population', 'Health', 'Agriculture', 'Development', 'Transport', 'Education', 'Social', 'Tourism', 'Finance','Business','Economy', 'Industry', 'Employment', 'Weather', 'Food', 'Energy', 'Infrastructure', 'Science&Technology', 'Government','Culture', 'Religion',
                 'Justice&Law', 'Country', 'Water Resource', 'Maritim', 'Military', 'International', 'Geography', 'Statistics', 'Others','Electronic','Biotechnology', 'Women', 'Gender', 'Cartography','Disability','Position','Marital','CDF','Research']

                 },
                 yAxis: {
                   min: 0,

                   title: {
                     text: 'Percentage (%)'
                   }
                 },
                 legend: {
               enabled: false
             },
             tooltip: {
               headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
               pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
                 '<td style="padding:0"><b>{point.y:.1f} %</b></td></tr>',
               footerFormat: '</table>',
               shared: true,
               useHTML: true
             },
             plotOptions: {
               column: {
                 pointPadding: 0.2,
                 borderWidth: 0
               }
             },
                 series: chartData

               });

             });
           }
         });
      </script>
   </head>
   <body class="hold-transition skin-blue sidebar-mini">
      <div id="container" style="width: 100%; min-height: 500px; margin: 0 auto"></div>
   </body>
</html>

这是从mysql中获取数据的代码

<?php
require('dbcon.php');

//select database



//define array
//we need two arrays - "male" and "female" so $arr and $arr1 respectively!
$arr    = array();
$result = array();

//get the result from the table "highcharts_data"
$sql = "select * from world";
$q = mysqli_query($con, $sql) or die(mysqli_error());
$j = 0;
while ($row = mysqli_fetch_assoc($q)) {

    //highcharts needs name, but only once, so give a IF condition
    if ($j == 0) {
        $arr['name'] = 'Percentage';

        $j++;
    }
    //and the data for male and female is here
    $arr['data'][] = $row['datavalue'];


}

//after get the data for male and female, push both of them to an another array called result
array_push($result, $arr); //1


//now create the json result using "json_encode"
print json_encode($result, JSON_NUMERIC_CHECK);

mysqli_close($con);
?>