ChartJS 根据日期更改显示的数据?

2022-01-22 00:00:00 jquery php javascript html chart.js

我有一个简单的部分,我在其中显示来自数据库的数据,在我的数据库中,我有两个共享sid"(会话 id)的表;我的桌子看起来像这样.

事件表id sid 目标按钮id1 1377Qqng1hn4866h7oh0t3uruu27dm5 是2 9021391Q86nog1028jnoqol8bqcrt182o7 无3 541Qqta8cs8s6kv60fei8i6jbesg36 是

还有

会话表id sid 日期时间1 1377Qqng1hn4866h7oh0t3uruu27dm5 2019-08-07 07:00:032 9021391Q86nog1028jnoqol8bqcrt182o7 2019-08-07 07:00:113 541QQta8cs8s6kv60fei8i6jbesg36 2019-08-13 09:56:51

我正在像这样在饼图上使用图表 js 显示这些数据

HTML

来自 <input type="text" id = "firstdatepicker" name = "firstdatepicker"> 的数据到<输入类型=文本"id=lastdatepicker"名称=lastdatepicker">

<块引用>

更新.

JS

 $(document).ready(function(){$.datepicker.setDefaults({日期格式:'yy-mm-dd'});$(函数(){$("#firstdatepicker").datepicker();$("#lastdatepicker").datepicker();});$('#filter').click(function(){var from_date = $('#firstdatepicker').val();var to_date = $('#lastdatepicker').val();if(from_date != '' && to_date != ''){$.ajax({url:"https://meed.audiencevideo.com/admin/chats/stats.php",类型:获取",数据:{from_date:from_date, to_date:to_date},成功:功能(数据){var session=数据[0].sessions;var 是 = 数据 [0].num_yes;var no =data[0].num_no;var ctx = document.getElementById("myPieChart");var myChart = new Chart(ctx, {类型:'馅饼',数据: {标签:[会话",是",否"],数据集:[{标签:性别",数据:[会话,是,否],背景颜色: ['rgba(255, 99, 132, 0.2)','rgba(54, 162, 235, 0.2)','rgba(54, 162, 235, 1)'],边框颜色: ['rgba(255,99,132,1)','rgba(54, 162, 235, 1)','rgba(255, 99, 132, 0.2)',],边框宽度:1}]},});}});}别的{alert("请选择日期");}});});

这里是 php.

error);}if (isset($_POST['firstdatepicker'])) {$firstDate= $_POST['firstdatepicker'];$lastDate= $_POST['lastdatepicker'];$sql = sprintf("SELECT count(*) as num_rows, datetime, count(distinct sid) as sessions, sum(targetbuttonname = 'yes') as num_yes, sum(targetbuttonname = 'no') as num_no from events AND time BETWEEN'$firstdate' AND '$lastdate' ORDER BY datetime DESC");}//$query =sprintf("SELECT SUM(sid) as session, COUNT(targetbuttonname) as yes FROM events WHERE targetbuttonname LIKE 'Yes'");$query = sprintf("SELECT count(*) as num_rows, count(distinct sid) as sessions, sum(targetbuttonname = 'yes') as num_yes, sum(targetbuttonname = 'no') as num_no from events;");//执行查询$result = $mysqli->query($query);//遍历返回的数据$数据 = 数组();foreach ($result as $row) {$数据[] = $行;}$result->close();$mysqli->close();打印 json_encode($data);

现在我想当用户在某些日期之间选择日期时,在饼图中它应该根据用户选择的日期显示数据.

不幸的是,现在当我选择日期数据仍然相同现场演示

我的代码做错了什么?

解决方案

既然你让我看看你的问题,我在这个片段中重新创建了整个客户端,一切都按预期工作.错误必须在 php 代码中.

我自己从未做过 php,但如果我发现它有什么问题,我会更新答案.如果我猜测一下,我会说您需要在某处使用 $sql.

//绕过CORSjQuery.ajaxPrefilter(函数(选项) {if (options.crossDomain && jQuery.support.cors) {options.url = 'https://cors-anywhere.herokuapp.com/' + options.url;}});//更新代码$(文档).ready(函数() {$.datepicker.setDefaults({日期格式:'yy-mm-dd'});$("#firstdatepicker").datepicker();$("#lastdatepicker").datepicker();$('#filter').click(function() {var from_date = $('#firstdatepicker').val();var to_date = $('#lastdatepicker').val();if (from_date != '' && to_date != '') {console.log(from_date, to_date);$.ajax({url: "https://meed.audiencevideo.com/admin/chats/stats.php",类型:获取",数据: {从_日期:从_日期,to_date: to_date},成功:函数(数据){控制台日志(数据[0])var session = data[0].sessions;var num_yes = 数据[0].num_yes;var num_no = 数据[0].num_no;var ctx = document.getElementById("myPieChart");var myChart = new Chart(ctx, {类型:'馅饼',数据: {标签:[会话",是",否"],数据集:[{标签:性别",数据:[会话,num_yes,num_no],背景颜色: ['rgba(255, 99, 132, 0.2)','rgba(54, 162, 235, 0.2)','rgba(54, 162, 235, 1)'],边框颜色: ['rgba(255,99,132,1)','rgba(54, 162, 235, 1)','rgba(255, 99, 132, 0.2)',],边框宽度:1}]},});}});} 别的 {alert("请选择日期");}});});

canvas {display: block;}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></脚本><script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.9.2/jquery.ui.datepicker.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script><link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.9.2/themes/sunny/jquery-ui.min.css"></链接><link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.css"></链接>来自<input type="text" id="firstdatepicker" name="firstdatepicker" value="19-08-13"><br>到 <输入类型="文本" id="lastdatepicker" name="lastdatepicker" value="19-08-14">

I have a simple section in which I am displaying data from the database , in my database I have two tables which shares 'sid` (session id); my tables looks like this.

Events table

id  sid                                    targetbuttonid

1   1377Qqng1hn4866h7oh0t3uruu27dm5        Yes
2   9021391Q86nog1028jnoqol8bqcrt182o7     No
3   541Qqta8cs8s6kv60fei8i6jbesg36         Yes

And

Sessions table

id  sid                                    datetime

1   1377Qqng1hn4866h7oh0t3uruu27dm5        2019-08-07 07:00:03
2   9021391Q86nog1028jnoqol8bqcrt182o7     2019-08-07 07:00:11
3   541Qqta8cs8s6kv60fei8i6jbesg36         2019-08-13 09:56:51

I am displaying these data using charts js on pie chart like this

HTML

<body>

        data from <input type="text" id = "firstdatepicker" name = "firstdatepicker">
        to  <input type="text" id = "lastdatepicker" name = "lastdatepicker">
            <input type="button" name="filter" id="filter" value="Filter" class="btn btn-info" /> 


        <canvas id="myPieChart" width="400" height="400"></canvas>
</body>

UPDATE.

JS

  $(document).ready(function(){  
       $.datepicker.setDefaults({  
            dateFormat: 'yy-mm-dd'   
       });  
       $(function(){  
            $("#firstdatepicker").datepicker();  
            $("#lastdatepicker").datepicker();  
       });  
       $('#filter').click(function(){  
            var from_date = $('#firstdatepicker').val();  
            var to_date = $('#lastdatepicker').val();  
            if(from_date != '' && to_date != '')  
            {  
                 $.ajax({  
                      url:"https://meed.audiencevideo.com/admin/chats/stats.php",  
                      type:"GET",  
                      data:{from_date:from_date, to_date:to_date},  
                      success:function(data){  
                        var session= data[0].sessions;
                        var yes = data[0].num_yes;
                        var no =data[0].num_no;
                        var ctx = document.getElementById("myPieChart");
                        var myChart = new Chart(ctx, {
                          type: 'pie',
                          data: {
                              labels: ["sessions","yes", "no"],
                              datasets: [{
                                label: 'Genders',
                                data: [session,yes, no],
                                backgroundColor: [
                                    'rgba(255, 99, 132, 0.2)',
                                    'rgba(54, 162, 235, 0.2)',
                                    'rgba(54, 162, 235, 1)'
                                ],
                                borderColor: [
                                    'rgba(255,99,132,1)',
                                    'rgba(54, 162, 235, 1)',
                                    'rgba(255, 99, 132, 0.2)',
                                ],
                                borderWidth: 1
                            }]
                        },

                        });
                      }  
                 });  
            }  
            else  
            {  
                 alert("Please Select Date");  
            }  
       });  
  });  

Here is php.

<?php
//setting header to json
header('Content-Type: application/json');

//database
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'vvvv');
define('DB_PASSWORD', 'vvvvv');
define('DB_NAME', 'vvvvv');

$firstdate = $_POST['firstdatepicker'];
$lastdate = $_POST['lastdatepicker'];
//get connection
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

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

if (isset($_POST['firstdatepicker'])) {

  $firstDate= $_POST['firstdatepicker'];
  $lastDate= $_POST['lastdatepicker'];

  $sql = sprintf("SELECT count(*) as num_rows, datetime, count(distinct sid) as sessions, sum( targetbuttonname = 'yes' ) as num_yes, sum( targetbuttonname = 'no' ) as num_no from events AND time BETWEEN '$firstdate' AND '$lastdate'  ORDER BY datetime DESC");
}

//$query =sprintf("SELECT SUM( sid ) as session , COUNT( targetbuttonname ) as yes FROM events WHERE targetbuttonname LIKE  'Yes'");
$query = sprintf("SELECT count(*) as num_rows, count(distinct sid) as sessions, sum( targetbuttonname = 'yes' ) as num_yes, sum( targetbuttonname = 'no' ) as num_no from events;");
//execute query
$result = $mysqli->query($query);

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

$result->close();

$mysqli->close();
print json_encode($data);

Now I want when user select date between certain dates, in pie chart it should display data based on those dates selected by user.

Unfortunately now when I select the dates data still the same live demo

What am I doing wrong in my codes?.

解决方案

Since you asked me to take a look at your question I recreated the whole client side in this snippet and it's all working as expected. The error must be in the php code.

I never did php myself but I'll updated the answer if I find what's wrong with it. If I were to take a guess I would say that you need to use the $sql somewhere.

// bypass CORS
jQuery.ajaxPrefilter(function(options) {
    if (options.crossDomain && jQuery.support.cors) {
        options.url = 'https://cors-anywhere.herokuapp.com/' + options.url;
    }
});
// updated code
$(document).ready(function() {
  $.datepicker.setDefaults({
    dateFormat: 'yy-mm-dd'
  });
  $("#firstdatepicker").datepicker();
  $("#lastdatepicker").datepicker();
  $('#filter').click(function() {
    var from_date = $('#firstdatepicker').val();
    var to_date = $('#lastdatepicker').val();
    if (from_date != '' && to_date != '') {
      console.log(from_date, to_date);
      $.ajax({
        url: "https://meed.audiencevideo.com/admin/chats/stats.php",
        type: "GET",
        data: {
          from_date: from_date,
          to_date: to_date
        },
        success: function(data) {
          console.log(data[0])
          var session = data[0].sessions;
          var num_yes = data[0].num_yes;
          var num_no = data[0].num_no;
          var ctx = document.getElementById("myPieChart");
          var myChart = new Chart(ctx, {
            type: 'pie',
            data: {
              labels: ["Sessions", "Yes", "No"],
              datasets: [{
                label: 'Genders',
                data: [session, num_yes, num_no],
                backgroundColor: [
                  'rgba(255, 99, 132, 0.2)',
                  'rgba(54, 162, 235, 0.2)',
                  'rgba(54, 162, 235, 1)'
                ],
                borderColor: [
                  'rgba(255,99,132,1)',
                  'rgba(54, 162, 235, 1)',
                  'rgba(255, 99, 132, 0.2)',
                ],
                borderWidth: 1
              }]
            },

          });
        }
      });
    } else {
      alert("Please Select Date");
    }
  });
});

canvas {display: block;}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.9.2/jquery.ui.datepicker.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>

<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.9.2/themes/sunny/jquery-ui.min.css"></link>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.css"></link>

data from <input type="text" id="firstdatepicker" name="firstdatepicker" value="19-08-13"><br> to <input type="text" id="lastdatepicker" name="lastdatepicker" value="19-08-14">
<input type="button" name="filter" id="filter" value="Filter" class="btn btn-info" />
<canvas id="myPieChart" width="400" height="400"></canvas>

相关文章