Josip Gòdly Zirdum Josip Gòdly Zirdum - 2 months ago 7
Ajax Question

Sometimes ajax database call return empty array?

I am trying to figure out why sometimes my php function returns an empty array. The event to trigger the ajax call is when a drop down is changed and it then hits my php function. Most of the time it returns the data from the database, but sometimes it doesn't, despite doing the exact same thing (changing the drop down) Any ideas on what can cause this? Basically I am using the console.log to check what is being returned and sometimes, nothing is. Despite other times with the same inputs it working just fine.

$(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();
}


Thanks.

Answer

Your id variable in javascript is always undefined.

In this line:

createQtrTable(qtrselection);

you need id

createQtrTable(qtrselection, id);
Comments