Refresh a table with jQuery/Ajax every 5 seconds

Refresh a table with jQuery/Ajax every 5 seconds

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Refreshing Data Tables Without Page Reloads

The goal is straightforward: maintain a live view of database records without interrupting the user's workflow by reloading the entire page. This pattern relies on polling, where client-side JavaScript periodically requests fresh data from the server and updates the DOM elements that hold the table content. To achieve this with jQuery and Ajax, you need three distinct components working in concert: a background timer to trigger requests, an endpoint to deliver the JSON payload, and logic to selectively update the HTML structure.

The simplest approach involves using setInterval to fire an Ajax request every five seconds. You must ensure the timer clears or resets if the user navigates away from the page, though for a static dashboard view, a persistent interval is often acceptable. The request itself should target an endpoint that returns only the necessary data structure—typically a JSON array of objects representing the rows.

const refreshInterval = 5000; // 5 seconds in milliseconds

setInterval(function() {
    $.ajax({
        url: '/api/refresh-data',
        method: 'GET',
        dataType: 'json',
        success: function(data) {
            updateTableContent(data);
        },
        error: function(xhr, status, error) {
            console.error('Failed to refresh data:', error);
            // Optional: Re-queue the request if a transient network failure occurs
        }
    });
}, refreshInterval);

The critical part of this implementation is the updateTableContent function. You cannot simply overwrite the entire <tbody> innerHTML without preserving row identifiers or managing scroll positions, which can lead to a jarring user experience. A robust strategy involves iterating over the incoming JSON array and mapping it to the existing DOM elements. If the table uses unique IDs for rows, you can find the corresponding elements and replace their text content. This preserves the table's layout, any attached event listeners like tooltips or click handlers, and the current scroll state.

function updateTableContent(rows) {
    const tbody = $('#tableBody');
    
    // Clear existing rows to prevent duplication
    tbody.empty();

    $.each(rows, function(index, row) {
        const tr = $('<tr></tr>');
        
        // Example: Reconstructing a simple 3-column row
        tr.append('<td>' + escapeHtml(row.name) + '</td>');
        tr.append('<td>' + escapeHtml(row.status) + '</td>');
        tr.append('<td>' + escapeHtml(row.timestamp) + '</td>');

        tbody.append(tr);
    });
}

function escapeHtml(text) {
    const map = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' };
    return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}

A significant trade-off in this architecture is the polling frequency. While five seconds provides near real-time updates, it generates ten requests per minute even when no data has changed. This places a continuous load on your server. If your backend logic involves expensive database queries or complex calculations for every single request, you risk hitting CPU limits or exceeding API rate limits before the next refresh cycle completes.

To mitigate this, consider implementing an exponential backoff mechanism in your JavaScript. If the server returns an HTTP 429 (Too Many Requests) status code, pause the timer and retry after a longer delay. Alternatively, shift the logic to the backend: have the server handle the polling interval and return data only when updates occur, but this requires changes to how you architect your API endpoints.

When integrating this into a Laravel application, ensure your controller method explicitly returns a JSON response with the Content-Type header set correctly. Using return response()->json($data); in Laravel handles this automatically. If you are using Blade templates for the initial page load, ensure that the jQuery script is included before the Ajax logic executes, and that the table elements have unique identifiers so they can be targeted efficiently for updates rather than full replacements.

Finally, be mindful of browser security restrictions known as Same-Origin Policy. Your client-side code must run on a domain that matches your server, or you must configure CORS headers in your Laravel middleware to allow cross-origin requests if necessary. This ensures that the Ajax calls function correctly without triggering security warnings in the developer console.

Our network