根据日期选择器中的选定日期绘制折线图(图表数据来自mysql)(日期来自mysql表)

时间:2019-05-01 11:24:22

标签: javascript php jquery mysql ajax

我试图根据日期选择器中提到的日期和ID绘制折线图的方法 Here i am selecting the ID and Date

That how i want to populate the line chart according to ID and Date

下面是我当前用于填充折线图的“我的代码”

HTML代码(显示图表)

<html>
<head>
    <title>Temperature chart</title>
</head>
<body>
                        <div id="chart-container">
                            <canvas id="mycanvas"></canvas>
                        </div>

    <script type="text/javascript" src="js/jquery-3.4.0.min.js"></script>
    <script type="text/javascript" src="js/Chart.min.js"></script>
    <script type="text/javascript" src="js/app.js"></script>
</body>
</html>

data.php(使用此文件从mysql获取数据并使用json打印)

<?php
//setting header to json
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: http://localhost:8080/hurry/data.php', false);
//database
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'canvasjs_db');

//get connection
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

if(!$mysqli){
  die("Connection failed: " . $mysqli->error);
}

//query to get data from the table
$query = sprintf("SELECT `temp`, `formatedate` FROM `datapoints` WHERE `device_id` = '50' AND `formatedate` >= '2019-04-02 09:26:00' AND `formatedate` <= '2019-04-03 13:26:00'");

//execute query
$result = $mysqli->query($query);

//loop through the returned data
$data = array();
foreach ($result as $row) {
  $data[] = $row;
}

//free memory associated with result
$result->close();

//close connection
$mysqli->close();

//now print the data
print json_encode($data);
?>

app.js(使用此文件填充图表中的数据)

$(document).ready(function(){
  $.ajax({
    url: "http://localhost:8080/Notifications/NewNotification/data.php",
    method: "GET",
    success: function(data) {
      console.log(data);
      var player = [];
      var score = [];

      for(var i in data) {
        player.push(data[i].formatedate);

        score.push(data[i].temp);
      }


      var chartdata = {
        labels: player,
        datasets : [
          {
            label: 'Temperature ',           
           hoverBackgroundColor: 'rgba(30, 0, 200)',
            hoverBorderColor: 'rgba(200, 200, 197)',
            data: score
          }

        ]

      };



      var ctx = $("#mycanvas");

      var lineGraph = new Chart(ctx, {
        type: 'line',

        data: chartdata
      });
    },
    error: function(data) {
      console.log(data);
    }

  });
});

0 个答案:

没有答案