How to view data from the selected elements from the dropdown menu using select2 to datatable.
How to view data from the selected elements from the dropdown menu using select2 to datatable.
wns
Posts: 12Questions: 8Answers: 0
I have problem in fetching the data based on selected elements from dropdown (select2) to yagra datatable. I dont know how to use the selected elements to back end query.
Select2 dropdown:
public function age(Request $request)
{
$data = [];
if($request->has('q')){
$search = $request->q;
$data = DB::table("user")
->select("id","age")
->where('age','LIKE',"%$search%")
->get();
}
return response()->json($data);
}
redirect to:
$('.age').select2({
placeholder: 'Select..',
ajax: {
url: '/select2-autocomplete-ajax_age',
dataType: 'json',
delay: 250,
processResults: function ($age) {
return {
results: $.map($age, function (item) {
console.log("Data success!");
console.log(item);
return {
text: item.age,
id: item.id,
}
})
};
},
cache: true
}
});
Backend query. (I dont sure how to fetch the selected elements into back end, actually. So I simply put $request->age):
public function filterQuery(Request $request){
$age= $request->age;
$query = User::query();
if(!empty($request->age)){
$query->where('age',$age);
}
$data = $query->get();
return datatables()->of($data)->make(true);
}
Route:
Route::get('select2-autocomplete-ajax_age', 'FiltersController@age');
Route::get('filter-result' , 'FiltersController@filterQuery');
This discussion has been closed.
Answers
I'm not clear how this relates to DataTables I'm afraid (other than the use of the third party yagra library)? Where is your
.age
element? Also, can you give us a link to the page please?Thanks,
Allan
The query from filterQuery() will fetch the selected elements from input dropdown (select2) into yagra datatable. However, I dont know how to call the selected elemets and pass the data to query.
My datatable() is
I'm sorry, I'm still not really understanding the question. Do you mean you aren't sure how to get the selected values from Select2? I think I might see the problem in the above code - you have:
But that's just static. It won't reflect any changes. Try:
which is a function that will be executed every time DataTables makes an Ajax call.
Allan