I am trying to fetch data from database on a table in my application. The code works fine using input box but I can't get it to work with select box. Note that I used select2 to filter data in the selectbox.
Here is the Route:
Route::get('get-student-info/', [ResultController::class, 'get_student_info'])->name('get_student_info');
Controller code:
public function get_student_info(Request $request)
{
$search_name=$request['search'] ?? "";
if ($search_name !=""){
$data=User::where('admission_num','like','%'.$search_name.'%')->get();
$output='';
if(count($data)>0){
$output ='
<table class="table">
<thead>
<tr>
<th scope="col">First Name</th>
<th scope="col">Last Name</th>
<th scope="col">Class</th>
</tr>
</thead>
<tbody>';
foreach($data as $row){
$output .='
<tr>
<th scope="row">'.$row->name.'</th>
<td>'.$row->lastname.'</td>
<td>'.$row->class.'</td>
</tr>
';
}
$output .= '
</tbody>
</table>';
}
else{
$output .='No results';
}
return $output;
}
}
Blade.php:
<div class="form-group">
<select class="form-select form-select-sm" name="search" id="search" aria-label="Default select example">
<option></option>
@foreach($admission as $admissions)
<option value="{{ $admissions->admission_num }}">{{ $admissions->admission_num }}</option>
@endforeach
</select>
</div>
<div id="search_list"></div>
<br><br>
</div>
<div class="col-lg-3"></div>
</div>
</div>
<script>
$(document).ready(function(){
$('#search').on('keyup',function(){
var query= $(this).val();
$.ajax({
url:"get-student-info",
type:"GET",
data:{'search':query},
success:function(data){
$('#search_list').html(data);
}
});
//end of ajax call
});
});
</script>
NOTE: The above code works perfectly when I used:
<input type="text" name="search" id="search" placeholder="Enter search name" class="form-control" onfocus="this.value=''">
But I cannot get it to work with selectbox.
My Answer:
Here is the Controller method:
php
public function get_student_info(Request $request)
{
$search = $request->get('search');
$students = Student::where('name', 'like', '%'.$search.'%')->get();
return response()->json($students);
}
And here is the JavaScript code to make an AJAX call to fetch data from the database and populate the select2 dropdown:
javascript
$('#student-select').select2({
ajax: {
url: '/get-student-info',
dataType: 'json',
delay: 250,
data: function (params) {
return {
search: params.term
};
},
processResults: function (data) {
return {
results: $.map(data, function (student) {
return {
id: student.id,
text: student.name
};
})
};
},
cache: true
}
});
Make sure to replace `#student-select` with the ID of your select box in your HTML code. This code will make an AJAX call to the `get_student_info` route and populate the select2 dropdown with the fetched data.
Rate this post
5 of 5 based on 6289 votesComments