有时ajax数据库调用返回空数组?

时间:2016-09-15 03:20:38

标签: php jquery ajax

我试图找出为什么有时我的php函数返回一个空数组。触发ajax调用的事件是当下拉列表被更改然后它命中我的php函数时。大多数情况下它会从数据库返回数据,但有时它并不是,尽管做了完全相同的事情(更改下拉列表)有什么想法可以导致这种情况?基本上我使用console.log来检查返回的内容,有时候,什么都没有。尽管其他时间使用相同的输入,但它的工作正常。

$(document).ready(function() {

$( "#qtrselect" ).change(function() {
    qtrselection = $( "#qtrselect" ).val();
    createQtrTable(qtrselection);
    $('#qtrselect').prop('disabled', true);

    setTimeout(function () {
     $('#qtrselect').prop('disabled', false);
}, 1000);

});    

} );

function createQtrTable(qtrselection, id) {

    $.ajax({
        type : 'POST',
        url  : 'createnewtable.php',
        data : {qtrdate: qtrselection, id: id},
        success :  function(response)
      {   
        response = jQuery.parseJSON(response);
          totalcommision = 0;
          totalpayments = 0;
          for (i = 0; i < response.length; i++) { 
            totalcommision += parseFloat(response[i][0]);
            totalpayments += parseFloat(response[i][3]);

          }
//I've cut out a bit here as it's not really needed to see the problem.
      }
   });

}

createnewtable.php

$qtrdate = $_POST['qtrdate'];
$id = $_POST['id'];
$startdate = '';
$enddate = '';

switch ($qtrdate) {
        case 0:
        $startdate = '2016-01-01' ;
        $enddate = '2018-12-30';
        break;
        case 1:
        $startdate = '2016-08-01' ;
        $enddate = '2016-10-31';     
        break;
        case 2:
        $startdate = '2016-11-01' ;
        $enddate = '2017-01-31';          
        break;
        case 3:
        $startdate = '2017-02-01' ;
        $enddate = '2017-04-30';
        break;
        case 4:
        $startdate = '2017-05-01' ;
        $enddate = '2017-07-31';      
        break;

}

  try
  { 

   $stmt = $db_con->prepare("SELECT com.commisionAmount, stu.studentName, pay.paymentDate, pay.paymentAmount FROM `commisions` as com INNER JOIN `accounts` as acc ON com.commisionAccount = acc.id INNER JOIN `studentpayments` as pay ON com.paymentID = pay.id INNER JOIN `students` as stu ON pay.paymentStudent = stu.id WHERE pay.paymentDate BETWEEN '$startdate' AND '$enddate' AND acc.id = '$id'");

    $stmt->execute();
   $results = $stmt->fetchAll();
  $results = json_encode($results);
      echo $results;

  }
  catch(PDOException $e){
   echo $e->getMessage();
  }

感谢。

1 个答案:

答案 0 :(得分:1)

javascript中的id变量始终未定义。

在这一行:

createQtrTable(qtrselection);

你需要id

createQtrTable(qtrselection, id);