Untitled
unknown
plain_text
a year ago
3.4 kB
4
Indexable
let lastSortedColumn = null; let lastSortAscending = false; // Start with false so the first click sorts ascending let currentPage = 1; // Define currentPage at the top level const rowsPerPage = 50; // Define the number of rows per page let totalRows = 0; // This will hold the total number of rows fetched function fetchData() { fetch('data.php') .then(response => response.json()) .then(data => { totalRows = data.length; // Update total number of rows displayData(data); // Call to function that handles data display updatePageInfo(); // Update pagination info }) .catch(error => { console.error('Error:', error); }); } function displayData(data) { const tableBody = document.getElementById('dataDisplay').getElementsByTagName('tbody')[0]; tableBody.innerHTML = ''; // Clear previous rows // Calculate which items to display based on current page const start = (currentPage - 1) * rowsPerPage; const end = start + rowsPerPage; const paginatedItems = data.slice(start, end); paginatedItems.forEach(item => { const row = document.createElement('tr'); row.innerHTML = `<td>${item.id}</td> <td>${item.temp}</td> <td>${item.humi}</td> <td>${item.press}</td> <td>${item.CO}</td> <td>${item.dist}</td> <td>${item.butt}</td> <td>${item.posi}</td>`; tableBody.appendChild(row); }); // Reapply sorting if there was a previous sort if (lastSortedColumn !== null) { sortByColumn(lastSortedColumn, lastSortAscending); } } function sortByColumn(columnIndex, ascending) { // Toggle the sort direction if the same column is clicked again if (lastSortedColumn === columnIndex) { ascending = !lastSortAscending; } lastSortedColumn = columnIndex; lastSortAscending = ascending; const table = document.getElementById('dataDisplay'); const rows = Array.from(table.querySelectorAll('tbody tr')); rows.sort((a, b) => { const aVal = a.children[columnIndex].textContent || a.children[columnIndex].innerText; const bVal = b.children[columnIndex].textContent || b.children[columnIndex].innerText; if (!isNaN(parseFloat(aVal)) && !isNaN(parseFloat(bVal))) { return ascending ? aVal - bVal : bVal - aVal; } return ascending ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal); }); rows.forEach(row => table.querySelector('tbody').appendChild(row)); } function nextPage() { const totalPages = Math.ceil(totalRows / rowsPerPage); if (currentPage < totalPages) { currentPage++; fetchData(); } } function previousPage() { if (currentPage > 1) { currentPage--; fetchData(); } } function updatePageInfo() { const pageInfo = document.getElementById('pageInfo'); pageInfo.textContent = `Page ${currentPage} of ${Math.ceil(totalRows / rowsPerPage)}`; } // Fetch data every 5 seconds to update the page in real time setInterval(fetchData, 5000); // Initial fetch fetchData();
Editor is loading...
Leave a Comment