I have a searchable select dropdown, and I want to fetch data from the inventory table, which now contains over 20,000 records. Previously, I used basic PHP and SQL to display data when the inventory had fewer than 2,000 records, and it worked fine. However, as the inventory has grown, I switched to using AJAX to improve performance, but it’s not working as expected. Could you help me identify where the issue might be?
<div class="form-floating form-floating-outline">
<select id="select2Basicc" class="select2 form-select form-select-lg" data-allow-clear="true" name="customer" required>
<option value="">Select Parts...</option>
</select>
<label for="select2Basicc">Select Customer</label> </div>
<code>
$(document).ready(function () {
// Initialize Select2 with AJAX
$('#select2Basicc').select2({
placeholder: 'Select Parts...',
ajax: {
url: 'get_parts.php', // Backend script to fetch data
type: 'GET',
dataType: 'json',
delay: 250, // Delay for better performance
data: function (params) {
return {
search: params.term, // Search term
page: params.page || 1 // Pagination
};
},
processResults: function (data) {
return {
results: data.items, // Items to display
pagination: {
more: data.pagination.more // Enable "Load More"
}
};
},
cache: true
},
minimumInputLength: 2 // Trigger search after 2 characters
});
});
and get_parts.php is
$search = $_GET['search']; $page = (int)($_GET['page']); $limit
= 10; $offset = ($page - 1) * $limit;
try {
$stmt = $conn_account_db->prepare("SELECT item_code FROM inventory WHERE item_code LIKE ? LIMIT ? OFFSET ?");
$likeSearch = "%$search%";
$stmt->bind_param("sii", $likeSearch, $limit, $offset);
$stmt->execute();
$result = $stmt->get_result();
$items = [];
while ($row = $result->fetch_assoc()) {
$items[] = [
'id' => $row['item_code'], // Value for the option
'text' => $row['item_code'] // Text to display
];
}
$stmt = $conn_account_db->prepare("SELECT COUNT(*) as total FROM inventory WHERE item_code LIKE ?");
$stmt->bind_param("s", $likeSearch);
$stmt->execute();
$totalResult = $stmt->get_result()->fetch_assoc();
$total = $totalResult['total'];
$more = ($offset + $limit) < $total;
echo json_encode([
'items' => $items,
'pagination' => ['more' => $more]
]);} catch (Exception $e) {
echo json_encode(['items' => [], 'pagination' => ['more' => false]]); }