I am trying to display the retrieved data in the respondent table from the database using the selected options from the multiple dropdowns. Still, the controller returns an empty array when I console.log the results even though the options match the database.
controller:
public function retrieveRowFromDatabase(Request $request)
{
$disease = $request->input('disease');
$vaccine = $request->input('vaccine');
$category = $request->input('category');
$envHazards = $request->input('env_hazards');
$age = $request->input('age');
$condition = $request->input('condition');
$sex = $request->input('sex');
$purok = $request->input('purok');
$start = $request->input('start');
$end = $request->input('end');
$respondent = Respondent::where([
'disease_id' => $disease,
'vaccine_id' => $vaccine,
])->get();
if ($respondent) {
return response()->json([
'success' => true,
'data' => $respondent
]);
} else {
return response()->json([
'success' => false,
'message' => 'No matching record found'
]);
}
}
this is the javascript and the ajax fires when the value of the dropdown changes and sends the request to the controller
<script type="text/javascript">
$(document).ready(function() {
function retrieveRowFromDatabase() {
var selectedValues = {
disease: $('#disease').val(),
vaccine: $('#vaccine').val(),
category: $('#category').val(),
env_hazards: $('#env_hazards').val(),
age: $('#age').val(),
condition: $('#condition').val(),
sex: $('#sex').val(),
purok: $('#purok').val(),
start: $('#start').val(),
end: $('#end').val()
};
console.log(selectedValues)
$.ajax({
url: '/retrieveRowFromDatabase',
type: 'POST',
data: { selectedValues, _token: '{{csrf_token()}}' },
dataType: 'json',
success: function(response) {
if (response.success) {
var rowData = response.data;
console.log(rowData);
$('#respondentTable tbody').empty();
var row = '<tr>';
for (var key in rowData) {
if (rowData.hasOwnProperty(key)) {
row += '<td>' + rowData[key] + '</td>';
}
}
row += '</tr>';
$('#respondentTable tbody').append(row);
} else {
console.error('Failed to retrieve row from the database.');
}
},
error: function(xhr, status, error) {
console.error('AJAX request error:', error);
}
});
}
$('#disease, #vaccine, #category, #env_hazards, #age, #condition, #sex, #purok, #start, #end').on('change', function() {
retrieveRowFromDatabase();
});
});
network tab in dev tools:
2
Answers
You can dump the request data and results to debug:
you should check if there’s objects in your collection using :
If there’s none, the problem come from your condition :
->get() return a collection instance, even if there’s no result. As such you need to check if there’s objects in your collection using :
Else it will always return true