How to Reload/Refresh jQuery DataTable on Button Click: Fixing fnReloadAjax Not Working Issue
jQuery DataTables is a powerful plugin that transforms ordinary HTML tables into interactive, feature-rich data grids. It supports sorting, searching, pagination, and dynamic data loading via AJAX—making it a staple in web applications for displaying tabular data. However, one common challenge developers face is reloading or refreshing the DataTable data on demand (e.g., after submitting a form, updating filters, or clicking a "Refresh" button).
A frequent pain point is the fnReloadAjax method not working as expected. This issue often arises due to version mismatches, deprecated APIs, or misunderstanding DataTables’ core functionality. In this blog, we’ll demystify DataTable reloading, explore why fnReloadAjax might fail, and provide a step-by-step guide to implementing a reliable reload mechanism using modern DataTables methods.
Table of Contents#
- Understanding the Need to Reload DataTables
- Prerequisites
- Common Methods to Reload DataTables
- Why
fnReloadAjaxIsn’t Working (And How to Fix It) - Step-by-Step Example: Reload DataTable on Button Click
- Troubleshooting Common Reload Issues
- References
Understanding the Need to Reload DataTables#
DataTables often fetch data dynamically via AJAX from a server. Over time, this data may change (e.g., new records added, existing ones updated/deleted). To reflect these changes without reloading the entire page, you need to reload the DataTable’s data. Common use cases include:
- After submitting a form to add/edit/delete a record.
- When a user applies new filters (e.g., date ranges, categories).
- Periodically refreshing data (e.g., real-time dashboards).
Prerequisites#
Before diving in, ensure you have the following set up:
- jQuery: DataTables depends on jQuery, so include it first.
- DataTables Library: Include the DataTables CSS and JS files (via CDN or local files).
- Basic Knowledge: Familiarity with jQuery, AJAX, and DataTable initialization.
CDN Links (place these in your HTML <head>):
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- DataTables CSS -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
<!-- DataTables JS -->
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>Common Methods to Reload DataTables#
Method 1: Using ajax.reload() (Modern DataTables API)#
DataTables 1.10+ introduced a revamped API with ajax.reload(), the recommended way to reload data. This method is part of the core DataTables API and works seamlessly with AJAX-driven tables.
Syntax:
table.ajax.reload( callback, resetPaging );callback: A function to run after reload completes (optional).resetPaging: A boolean (true/false) to reset pagination to the first page (default:true).
Method 2: The Deprecated fnReloadAjax#
fnReloadAjax was a popular plugin for older DataTables versions (pre-1.10) to reload AJAX data. However:
- It was not part of the core DataTables library (you had to include a separate plugin).
- It is deprecated in DataTables 1.10+ (replaced by the official
ajax.reload()method).
Why fnReloadAjax Isn’t Working (And How to Fix It)#
If fnReloadAjax fails, it’s likely due to one of these reasons:
1. Using DataTables 1.10+ Without the Plugin#
fnReloadAjax was never part of core DataTables. It was a community-contributed plugin for DataTables 1.9.x and earlier. In DataTables 1.10+, the API was rewritten, and fnReloadAjax is no longer supported by default.
Fix: Migrate to ajax.reload() (see Method 1).
2. Missing the fnReloadAjax Plugin#
If you’re stuck on an older DataTables version (pre-1.10) and need fnReloadAjax, ensure you include the plugin script. You can find the plugin here (note: this link may be outdated, as the plugin is no longer maintained).
Warning: Using deprecated plugins risks security issues and compatibility problems. Upgrade to ajax.reload() for long-term stability.
3. Incorrect API Usage#
Older DataTables used fn-prefixed methods (e.g., fnReloadAjax), while modern versions (1.10+) use a camelCase API (e.g., ajax.reload()). Mixing these will cause errors.
Fix: Use the modern API: initialize DataTables with $('#table').DataTable() (capital D) to access the new API.
Step-by-Step Example: Reload DataTable on Button Click#
Let’s build a working example with a DataTable that loads data via AJAX and a "Refresh" button to reload it.
Step 1: Set Up HTML Structure#
Create a table and a reload button in your HTML:
<!-- Reload Button -->
<button id="reloadBtn" class="btn btn-primary">Refresh Data</button>
<!-- DataTable Container -->
<table id="myTable" class="display">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody></tbody> <!-- Data will load here via AJAX -->
</table>Step 2: Initialize DataTable with AJAX#
Initialize the DataTable to fetch data from a server endpoint (e.g., /api/users). We’ll use a mock API for demonstration (you can replace it with your real endpoint).
// Initialize DataTable and store the instance in a variable
let table;
$(document).ready(function() {
table = $('#myTable').DataTable({
ajax: {
url: 'https://jsonplaceholder.typicode.com/users', // Mock API (replace with your endpoint)
dataSrc: '' // Use empty string if API returns an array directly
},
columns: [
{ data: 'id' },
{ data: 'name' },
{ data: 'email' }
],
paging: true,
searching: true
});
});Step 3: Add a "Refresh" Button#
We already added the button in Step 1. Now, style it (optional) using CSS:
#reloadBtn {
margin: 20px 0;
padding: 8px 16px;
cursor: pointer;
}Step 4: Implement Reload Logic with ajax.reload()#
Add a click handler to the button that calls ajax.reload() on the DataTable instance:
$(document).ready(function() {
// ... (DataTable initialization from Step 2)
// Reload button click handler
$('#reloadBtn').on('click', function() {
// Show a loading message (optional)
$(this).text('Loading...').prop('disabled', true);
// Reload DataTable data
table.ajax.reload(
// Callback after reload completes
function(json) {
console.log('Data reloaded successfully!', json);
$('#reloadBtn').text('Refresh Data').prop('disabled', false); // Reset button
},
false // Do NOT reset pagination (optional; default: true)
);
});
});Key Details:#
tableVariable: We stored the DataTable instance intableto access it later in the button click handler.ajax.reload()Parameters:- The first argument is a callback function that runs after the reload finishes (use this to update UI, e.g., resetting the button text).
- The second argument (
falsein the example) prevents pagination from resetting to the first page. Set totrue(default) to reset pagination.
Troubleshooting Common Reload Issues#
1. DataTable Instance Not Accessible#
Issue: table.ajax.reload() throws an error like Uncaught TypeError: Cannot read properties of undefined (reading 'ajax').
Cause: The table variable is out of scope or not initialized.
Fix: Ensure table is declared globally (or in a scope accessible to the button click handler) and initialized after the DOM is ready.
2. AJAX Response Format Mismatch#
Issue: DataTable shows "No data available in table" after reload.
Cause: The server’s AJAX response doesn’t match DataTable’s expected format. By default, DataTable expects data in { data: [...] }, but we used dataSrc: '' in the example because our mock API returns a raw array.
Fix:
- If your server returns
{ data: [...] }, removedataSrc: ''. - Use
dataSrcto specify the nested array (e.g.,dataSrc: 'records'if the response is{ records: [...] }).
3. Cached AJAX Responses#
Issue: Data doesn’t update because the browser caches the AJAX request.
Fix: Add cache: false to the DataTable’s AJAX configuration to force a fresh request:
ajax: {
url: 'https://jsonplaceholder.typicode.com/users',
dataSrc: '',
cache: false // Disable caching
}4. Server-Side Processing Issues#
Issue: Reload fails with server-side processing (serverSide: true).
Cause: Server-side processing requires the server to handle pagination, sorting, and filtering. The reload may not send updated parameters.
Fix: Use ajax.data to pass dynamic parameters (e.g., filters) on reload:
ajax: {
url: 'your-server-endpoint',
data: function(d) {
// Pass dynamic parameters (e.g., from a filter input)
d.startDate = $('#startDate').val();
}
}References#
- DataTables Official
ajax.reload()Documentation - DataTables Initialization Guide
- jQuery AJAX Documentation
- DataTables
fnReloadAjaxPlugin (Legacy) - Stack Overflow: "How to reload DataTable data?"
By following this guide, you can reliably reload DataTable data using ajax.reload()—the modern, supported method. Avoid deprecated plugins like fnReloadAjax and leverage the official API for a smoother experience. Let us know in the comments if you encountered other issues!