I am fetching record with drop down using ajax call but the problem is that it is fetching only one record while there are three records in the database
This is my PHP code:
<?php
include 'config/dbconfig.php';
$genid = $_POST['id'];
$operatorId = $_POST['operatorId'];
$query = mysqli_query($con, "SELECT * FROM generatorrun WHERE generatorId='$genid' AND operatorId='$operatorId'");
while($result = mysqli_fetch_array($query)) {
$turnOn = $result['startTime'];
$turnOff = $result['endTime'];
$datetime1 = new DateTime($turnOn);
$datetime2 = new DateTime($turnOff);
$interval = $datetime1->diff($datetime2);
$datedifference = $interval->format('%Y-%m-%d %H:%i:%s');
$startReading = $result['startReading'];
$endReading = $result['endReading'];
$dailyConsumption = $endReading - $startReading;
$postData = array(
"turnOn" => $turnOn,
"turnOff" => $turnOff,
"runningTime" => $datedifference,
"startReading" => $startReading,
"endReading" => $endReading,
"dailyConsumption" => $dailyConsumption,
);
}
echo json_encode($postData);
?>
I have to fetch the values from MySQL and stored in an associative array and then encoding it with json_encode()
function.
and this is the code for fetching the record in jquery:
<script>
$(document).ready(function () {
$(".bg-yellow").hide();
$(".bg-red").hide();
$("#getGen").change(function () {
var id = $('#getGen').val();
var operatorId = $(".opid").val();
$.ajax({
type: "POST",
url: 'getGenerator.php',
data: {id: id, operatorId: operatorId},
success: function (response) {
var data = jQuery.parseJSON(response);
$(".turnOn").html(data.turnOn);
$(".turnOff").html(data.turnOff);
$(".running").html(data.runningTime);
$(".startReading").html(data.startReading);
$(".endReading").html(data.endReading);
$(".dailyConsumption").html(data.dailyConsumption);
$(".bg-yellow").show();
$(".bg-red").show();
}
});
});
});
</script>
the problem is that it is fetching only one record and I have used while loop to iterate through all records which are in MySQL table but it is only fetching only one record