简体   繁体   中英

PHP and Ajax: using post ajax return error

I have data which is returned from the database, I am displaying them on a pie chart using chartjs.

I want the user to select a specific range of date and when she clicks filter it should display data on pie chart based on dates selected by a user, live demo

Here is my solution.

HTML

    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" /> 

JS

$(document).ready(function(){

  $(function() {
    $( "#firstdatepicker" ).datepicker();
    $( "#lastdatepicker").datepicker();
  }); 

   $('#filter').click(function(){  
        var from_date =$('#firstdatepicker').datepicker({ dateFormat: 'yy-mm-dd' }).val();
        var to_date =$('#lastdatepicker').datepicker({ dateFormat: 'yy-mm-dd' }).val();
        if(from_date != '' && to_date != ''){

             $.ajax({  
                  url:"https://meed.audiencevideo.com/admin/chats/stats.php",  
                  type:"POST",  
                  data:{from_date:from_date, to_date:to_date},  
                  success:function(data){  
                     console.log(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)'
                            ],
                            borderWidth: 1
                        }]
                    },           
                    });
                  },
                  error: function () {
                    console.log('Something went wrong');
                  }
             });  
        }  
        else  
        {  
             alert("Please Select Date");  
        }  
   });  
})

Here is php to grab the data from database

if (isset($_POST['from_date']) && isset($_POST['to_date'])) {
  $firstDate= $_POST['from_date'];
  $lastDate= $_POST['to_date'];
  $firstDate_new = date('Y-m-d', strtotime($firstDate));
  $lastDate_new = date('Y-m-d', strtotime($lastDate));

  $query = 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 WHERE datetime BETWEEN '{$firstDate_new}' AND '{$lastDate_new}'");
  var_dump($query);

  $result = $mysqli->query($query);
  $data = [];
  if(mysqli_num_rows($result) > 0)  
  {  
       while($row = mysqli_fetch_array($result))  
       {  
        $data[] = $row; 
       }  
  }  

  echo json_encode($data);
  exit;

}else{

//query to get data from the table
$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);

//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);

when I select the range of date and click filter I get the data I need on a console like this.

"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 WHERE datetime BETWEEN '2019-08-13' AND '2019-08-14'"


[  
   {  
      "0":"12",
      "num_rows":"12",
      "1":"2019-08-14",
      "datetime":"2019-08-14",
      "2":"12",
      "sessions":"12",
      "3":"2",
      "num_yes":"2",
      "4":"4",
      "num_no":"4"
   }
]

I am getting an error from ajax something is wrong . when I tried to change from POST to GET data are displayed but old data.

What I am doing wrong with my codes??

change you ajax part with below code

$(document).ready(function(){
  $(function() {
    $( "#firstdatepicker" ).datepicker();
    $( "#lastdatepicker").datepicker();
  }); 
   $('#filter').click(function(){  
        var from_date =$('#firstdatepicker').datepicker({ dateFormat: 'yy-mm-dd' }).val();
        var to_date =$('#lastdatepicker').datepicker({ dateFormat: 'yy-mm-dd' }).val();
        if(from_date != '' && to_date != ''){
             $.ajax({  
                  url:"https://meed.audiencevideo.com/admin/chats/stats.php",  
                  type:"POST",
                  dataType:"json",
                  data: { 
                          from_date: from_date, 
                          to_date: to_date
                         },  
                  success:function(data){  
                     console.log(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)'
                            ],
                            borderWidth: 1
                        }]
                    },           
                    });
                  },
                  error: function () {
                    console.log('Something went wrong');
                  }
             });  
        } else  {  
             alert("Please Select Date");  
        }  
   });  
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM