Given the following code: public function orders() { $webdoctorbrown =…
- User
Given the following code: public function orders() { system_settings = get_settings('system_settings', true);
if ((!isset($web_doctor_brown) || empty($web_doctor_brown))) { /* redirect him to the page where he can enter the purchase code */ redirect(base_url("admin/purchase-code")); } if ((isset($system_settings['is_web_under_maintenance']) && $system_settings['is_web_under_maintenance'] == 1)) { /* redirect him to the page where he can enter the purchase code */ redirect(base_url("maintenance")); } if ($this->ion_auth->logged_in()) { $this->data['main_page'] = 'orders'; $this->data['title'] = '我的訂單 | ' . $this->data['web_settings']['site_title']; $this->data['keywords'] = '我的訂單, ' . $this->data['web_settings']['meta_keywords']; $this->data['description'] = '我的訂單 | ' . $this->data['web_settings']['meta_description']; $total = fetch_orders(false, $this->data['user']->id, false, false, 1, NULL, NULL, NULL, NULL); $limit = 10; $config['base_url'] = base_url('my-account/orders'); $config['total_rows'] = $total['total']; $config['per_page'] = $limit; $config['num_links'] = 2; $config['use_page_numbers'] = TRUE; $config['reuse_query_string'] = TRUE; $config['page_query_string'] = FALSE; $config['uri_segment'] = 3; $config['attributes'] = array('class' => 'page-link'); $config['full_tag_open'] = '<ul class="pagination justify-content-center">'; $config['full_tag_close'] = '</ul>'; $config['first_tag_open'] = '<li class="page-item">'; $config['first_link'] = 'First'; $config['first_tag_close'] = '</li>'; $config['last_tag_open'] = '<li class="page-item">'; $config['last_link'] = 'Last'; $config['last_tag_close'] = '</li>'; $config['prev_tag_open'] = '<li class="page-item">'; $config['prev_link'] = '<i class="fa fa-arrow-left"></i>'; $config['prev_tag_close'] = '</li>'; $config['next_tag_open'] = '<li class="page-item">'; $config['next_link'] = '<i class="fa fa-arrow-right"></i>'; $config['next_tag_close'] = '</li>'; $config['cur_tag_open'] = '<li class="page-item active"><a class="page-link">'; $config['cur_tag_close'] = '</a></li>'; $config['num_tag_open'] = '<li class="page-item">'; $config['num_tag_close'] = '</li>'; $page_no = (empty($this->uri->segment(3))) ? 1 : $this->uri->segment(3); if (!is_numeric($page_no)) { redirect(base_url('my-account/orders')); } $offset = ($page_no - 1) * $limit; $this->pagination->initialize($config); $this->data['links'] = $this->pagination->create_links(); $this->data['orders'] = fetch_orders(false, $this->data['user']->id, false, false, $limit, $offset, 'date_added', 'DESC', NULL, NULL, NULL, NULL, NULL, NULL, NULL, '', true); foreach($this->data['orders'] as $order){ $this->requestPaymentStatus($order[0]['payment_refer_no'], $order[0]['id']); } $this->data['order_items'] = fetch_order_data_structured($this->data['user']->id); $this->data['payment_methods'] = get_settings('payment_method', true); $this->load->view('front-end/' . THEME . '/template', $this->data); } else { redirect(base_url(), 'refresh'); } }I want to develop the load more function trigger by user scroll down.
- Assistant
To implement a "load more" feature triggered by user scroll down, you'll typically use AJAX to fetch the next page of data without reloading the page.
Here’s a step-by-step plan based on your code and HTML:
Backend (Controller) Preparation
Your existing
orders()method has pagination with$limitand$offset. We should expose an API endpoint that accepts the page number (or offset) and returns the next batch of orders as JSON.Create a new function, e.g.
orders_ajax()to respond to AJAX requests:public function orders_ajax() { if (!$this->ion_auth->logged_in()) { echo json_encode(['error' => 'Unauthorized']); return; } $page_no = $this->input->get('page_no'); $limit = 10; $offset = ($page_no - 1) * $limit; $user_id = $this->data['user']->id; $orders = fetch_orders( false, $user_id, false, false, $limit, $offset, 'date_added', 'DESC', NULL, NULL, NULL, NULL, NULL, NULL, NULL, '', true ); foreach ($orders as $order) { $this->requestPaymentStatus($order[0]['payment_refer_no'], $order[0]['id']); } // Format data for JSON output or pass prepared HTML // Example: Return partial rendered HTML for the orders, or just JSON data // We'll assume JSON of orders for flexible frontend rendering echo json_encode([ 'orders' => $orders, 'next_page' => count($orders) < $limit ? null : $page_no + 1 ]); }Add a route for this method in your routes config if needed.
Frontend (JavaScript and HTML)
In your provided HTML, you have a container
<div id="new-order-list-content"></div>— this is where we'll append new orders.First, set an initial page counter variable and a flag to prevent multiple simultaneous loads:
<script> document.addEventListener('DOMContentLoaded', function() { let pageNo = 1; const limit = 10; let loading = false; let noMoreData = false; const content = document.getElementById('new-order-list-content'); // Function to create HTML for orders function renderOrders(orders) { let html = ''; orders.forEach(order => { // Customize the HTML as per your order structure // Example assumes order contains fields like id and date_added html += ` <div class="order-item" data-order-id="${order[0].id}"> <h3>Order ID: ${order[0].id}</h3> <p>Date: ${order[0].date_added}</p> <!-- Add other order details --> </div> `; }); return html; } // Fetch orders from server function loadOrders() { if (loading || noMoreData) return; loading = true; pageNo++; fetch(`<?= base_url('my-account/orders_ajax') ?>?page_no=${pageNo}`) .then(response => response.json()) .then(data => { if (data.error) { console.error(data.error); return; } if (data.orders.length === 0) { noMoreData = true; } else { const html = renderOrders(data.orders); content.insertAdjacentHTML('beforeend', html); if (!data.next_page) noMoreData = true; } }) .catch(error => console.error('Error fetching orders:', error)) .finally(() => { loading = false; }); } // Initial load (page 1 orders are presumably already loaded server-side) // Just append if you want to load page 1 here too: // loadOrders(); // Scroll event listener to trigger load more window.addEventListener('scroll', function() { if (loading || noMoreData) return; // Check if user scrolled near bottom (e.g., 100px from bottom) if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 100) { loadOrders(); } }); }); </script>
Summary:
- Create a PHP controller method
orders_ajaxwhich returns JSON orders for a given page. - Use JavaScript to detect scroll near the page bottom.
- Fetch next page’s orders from
orders_ajaxendpoint via AJAX. - Append new orders to the
.new-order-list-contentdiv. - Stop loading when no more data is available.
Bonus: Handling Search / Filter
Your snippet shows a search input box with class
new-order-list-search-input. You can enhance the AJAX URL by sending the search query as well to filter orders server-side.
If you want me to help setting up the API with search or provide the HTML template for order items, please share the expected order data structure or existing HTML for an order item.
- Create a PHP controller method
- User
FYI: The full code of the html, css and js in page:
Please based on the above code to modify your code
- Assistant
Thanks for sharing the full HTML+JS+CSS and your data structure! Your current frontend renders all orders grouped by date, then by order, seller, product, based on the full data loaded in the page (
orderData).
Goal:
Implement "Load More" triggered by scroll, fetching next page orders via AJAX (server-side pagination), and append these new orders properly into the existing grouped UI.
What needs to change?
-
Backend
Provide an API (e.g.,orders_ajax) to return paginated order data in the same shape structure asorderDataso that the frontend can reuse your existing grouping & rendering logic. -
Frontend
Modify your JS to:- Control current page number and loading state
- On scroll near bottom, call the API for page N+1
- Merge the newly fetched
orderDatawith existingorderData - Re-render the list (or smartly update UI, but re-render is simpler here)
- Note: If re-rendering the whole list, scroll position can jump. So alternatively append only new rendered DOM (more complex).
-
Optionally: On search input, reset pagination and data.
Step-by-step solution
1) Backend — Add paged orders API
Add method in your controller:
public function orders_ajax() { if (!$this->ion_auth->logged_in()) { echo json_encode(['error' => 'Unauthorized']); return; } $page_no = intval($this->input->get('page_no')); if ($page_no < 1) $page_no = 1; $limit = 10; $offset = ($page_no - 1) * $limit; $user_id = $this->data['user']->id; // Pass any necessary params - adjust fetch_orders params accordingly - fetch_orders returns key data array if true last param // Assuming fetch_orders(...) returns raw orders list; you may need to process this similarly to $order_items. // You probably have a method similar to prepare $order_items structure — do that here. $orders_raw = fetch_orders( false, $user_id, false, false, $limit, $offset, 'date_added', 'DESC', NULL, NULL, NULL, NULL, NULL, NULL, NULL, '', true ); // You need to format $orders_raw into the same structure as $order_items // Assuming there's a function `fetch_order_data_structured` that does this: $order_items = fetch_order_data_structured($user_id, $orders_raw); // If no more data $noMoreData = empty($order_items); echo json_encode([ 'order_items' => $order_items, 'no_more_data' => $noMoreData, 'page_no' => $page_no ]); }Make sure you expose this via URL
my-account/orders_ajax(adjust routes if needed).
2) Frontend - update your JS:
Modify your existing immediate function
(() => { ... })();Add these:
(() => { let orderData = <?=json_encode($order_items)?>; // initial data loaded from server let currentPage = 1; const LIMIT = 10; let loading = false; let noMoreData = false; // ... your existing constants, functions (formatDateOnly, createProductItem, groupOrders, renderGroupedOrders, etc) intact // We will keep your existing renderCurrentList and groupOrders usage. // Modified renderCurrentList to just re-render the whole list: function renderCurrentList() { renderGroupedOrders(groupOrders(orderData)); } // Append new order items fetched from server to orderData (merge object) // orderData structure is keyed by sellerId, each seller has orders obj, etc. function mergeOrderData(newData) { // newData has same structure, we merge sellers + their orders: for (const [sellerId, seller] of Object.entries(newData)) { if (!orderData[sellerId]) { orderData[sellerId] = seller; } else { // merge orders for (const [orderNumber, order] of Object.entries(seller.orders)) { if (!orderData[sellerId].orders[orderNumber]) { orderData[sellerId].orders[orderNumber] = order; } else { // If you think an order can appear twice with different products, you may merge products array here: // For now, assume no duplicates } } } } } // Load next page via ajax async function loadNextPage() { if (loading || noMoreData) return; loading = true; currentPage++; try { const response = await fetch(`<?=base_url('my-account/orders_ajax')?>?page_no=${currentPage}`, { credentials: 'same-origin' }); if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`); const data = await response.json(); if (data.error) { console.error("Error from server AJAX:", data.error); return; } if(data.no_more_data) { noMoreData = true; } mergeOrderData(data.order_items); renderCurrentList(); } catch (e) { console.error("Failed to load orders:", e); } finally { loading = false; } } // Scroll listener triggers load more at bottom window.addEventListener('scroll', () => { if (loading || noMoreData) return; // Trigger when scrolled within 150px of bottom if ((window.innerHeight + window.scrollY) >= (document.body.offsetHeight - 150)) { loadNextPage(); } }); // If you want to reset and reload on search, modify your searchInput input listener accordingly: searchInput.addEventListener("input", e => { const val = e.target.value.trim(); if (!val) { clearSearchResults(); // Reset pagination and reload initial data on empty search currentPage = 1; noMoreData = false; // You might want to reload orderData fully from server here as well if you want fresh data // For now just re-render initial full data: renderGroupedOrders(groupOrders(orderData)); return; } const results = searchItems(val); renderSearchResults(results); }); // Initial render with first page data from PHP renderCurrentList(); })();
3) Notes / Improvements
- Merging data: This naïve
mergeOrderDataassumes no duplication. If same orders/product may appear on different pages, you may want a deep-merge strategy (appending products arrays carefully). - Scroll Position Jumps: Re-rendering entire list may cause scroll jump.
To prevent this, either append only newly rendered elements, or preserve scroll position usingscrollTopadjustments. - Search: Currently filters the loaded data only. For large datasets, consider implementing backend search API.
- Initial data size: Since the first page is loaded in PHP, your JS initializes with that, then loads page 2+ on scroll.
- Loading indicator: You can add a spinner or message while loading.
- Error handling: Extend as needed for user feedback.
If you want help improving smooth append-only render or integration with your popups etc. just ask!
Summary
- Create
orders_ajaxreturning paginated portion of data similarly structured as initialorderData. - In JS maintain current page state, on scroll page+1 fetched and merged.
- Re-render UI to show accumulated orders grouped by date, order, seller.
- Keep your current grouping and rendering functions unchanged, just reuse them with merged data.
If you want, I can help you generate the PHP function to convert your database query results to the complex
$order_itemsstructure exactly like you have. Just let me know! -
- User
Given the following code in controller for update the status when the user confirm the item delivery: public function confirm_delivery() { this->form_validation->set_rules('user_id', 'user id', 'trim|required|numeric|xss_clean'); if (!this->form_validation->run()) { this->response['error'] = true; this->response)); }
$order_itme_data = fetch_details("order_items", ["id" => $_POST['order_item_id']]); if(isset($order_itme_data) || !empty($order_itme_data) || count($order_itme_data) > 0){ if($order_itme_data[0]['user_id'] != $_POST['user_id']){ $this->response['error'] = true; $this->response['message'] = "不匹配的用戶記錄"; return print_r(json_encode($this->response)); } $this->response = $this->order_model->confirm_delivery($_POST['order_item_id']); $this->response['error'] = false; $this->response['message'] = "已成功確認收貨,請給予評價"; } else { $this->response['error'] = true; $this->response['message'] = "找不到訂單物品"; } print_r(json_encode($this->response)); }Update the following to execute the ajax: if (product.status === 4) { const confirmBtn = document.createElement("button"); confirmBtn.type = "button"; confirmBtn.className = "new-order-list-btn new-order-list-btn-confirm"; confirmBtn.textContent = "確定收貨"; confirmBtn.setAttribute("aria-label",
確定收貨:${product.name}); confirmBtn.addEventListener("click", () => { //alert(您已確定收貨:${product.name});product.status = 5; product.confirmed = true; renderCurrentList(); }); btnsDiv.appendChild(confirmBtn); } - Assistant
To update your JavaScript to make an AJAX call to your
confirm_deliverycontroller method when the user clicks the "確定收貨" button, you can replace the current in-memory status update with an asynchronous fetch request that calls your backend endpoint.
Here is the updated code snippet for that button's event listener:
if (product.status === 4) { const confirmBtn = document.createElement("button"); confirmBtn.type = "button"; confirmBtn.className = "new-order-list-btn new-order-list-btn-confirm"; confirmBtn.textContent = "確定收貨"; confirmBtn.setAttribute("aria-label", `確定收貨:${product.name}`); confirmBtn.addEventListener("click", async () => { if (!confirm(`確定要確認收貨「${product.name}」嗎?`)) return; try { confirmBtn.disabled = true; confirmBtn.textContent = "確認中..."; const userId = <?= $this->data['user']->id ?>; // Inject user ID from PHP into JS const formData = new FormData(); formData.append('order_item_id', product.id); // assuming product.id matches order_item_id formData.append('user_id', userId); const response = await fetch('<?= base_url("my-account/confirm_delivery") ?>', { method: 'POST', body: formData, credentials: 'same-origin', headers: { 'X-Requested-With': 'XMLHttpRequest' // optional, sometimes needed to detect AJAX } }); const data = await response.json(); if (data.error) { alert('錯誤: ' + data.message); confirmBtn.disabled = false; confirmBtn.textContent = "確定收貨"; } else { alert(data.message || '已成功確認收貨'); // Update product status in client-side data: product.status = 5; product.confirmed = true; renderCurrentList(); } } catch (error) { alert('無法提交請求,請稍後重試。'); console.error('Confirm delivery error:', error); confirmBtn.disabled = false; confirmBtn.textContent = "確定收貨"; } }); btnsDiv.appendChild(confirmBtn); }
Explanation:
- Added a
confirm()popup to prevent accidental clicks. - Created a
FormDataobject to send theorder_item_idanduser_idusing POST as expected by your backend. - Used
fetchwithawaitto call your backend API endpoint. - Handled error and success responses accordingly.
- Disabled button during request to prevent duplicate submissions.
- On success, updated local
product.statusand re-rendered the list. - Injected
user_idfrom PHP into JS for security and correctness (make sure$this->data['user']->idis available in your PHP view).
Notes:
- Make sure your Controller method is accessible via the URL (in this example I used
my-account/confirm_delivery, adjust as necessary). - Ensure you have CSRF protection handled on your server (CodeIgniter has built-in CSRF token protection you may want to pass to the AJAX).
- If
product.idis not the same asorder_item_idexpected by backend, adjust accordingly.
If you want, I can help you further to handle CSRF tokens or show a loading spinner instead of plain text, just let me know!
- Added a