One common issue is ensuring that the data being returned by the AJAX call is correctly structured and accessible. Here is the updated JavaScript.
$(document).ready(function() {
$('#search').select2({
placeholder: 'Search for an item',
ajax: {
url: '{{ route('search') }}', // Ensure this is the correct route
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
id: item.id,
text: item.name,
name: item.name,
email: item.email
}
})
};
},
cache: true
}
});
$('#search').on('select2:select', function (e) {
var data = e.params.data; // Access the data directly
$('#customer-name').val(data.name);
$('#customer-email').val(data.email);
});
});
in the Controller
public function customers(Request $request)
{
$search = $request->get('q');
$data = Customer::where('name', 'LIKE', "%{$search}%")->limit(10)->get();
return response()->json($data);
}