I am building a search form with a search results table. Using jQuery and DataTables.
Possibly Overly-Long Preamble
Example (simplified) Form:
<form id="frmSearchQuery">
<input name="author" type="text">
<input name="title" type="text">
<button id="btnSubmitSearch" type="submit">Search</button>
</form>
with
$("#frmSearchQuery").submit(onFormSubmit);
Example (simplified) Table:
<table id="tblSearchResults" style="display:none">
<thead>
<tr>
<th>Author</th>
<th>Title</th>
<th>Actions</th>
</tr>
</thead>
</table>
(it is hidden initially)
Example JavaScript:
function onFormSubmit(event) {
// validate and sanitise form data
$.ajax({
url: ...,
method: "POST",
data: ...,
// painstaking but irrelevant details omitted for brevity
}).done(onSearchQuerySuccess).fail(onSearchQueryFailure);
}
function onSearchQuerySuccess(resultsList) {
$("#tblSearchResults").DataTable({
...
data: resultsList,
...
});
$("#tblSearchResults").show();
}
So far so good. On searching, the results are returned from the server and shown in the table, which is now visible. The first time I search.
However, if I search again (without reloading the page), DataTable is already initialised and so rendering the table fails.
If I were calling an AJAX endpoint from the table, I would be able to use ajax.reload().
I tried initialising the DataTable once at the beginning.
function initTable() {
$tblSearchResults = $("#tblSearchResults").DataTable({
...
data: resultsList,
...
});
}
using a page-global variable for the resultsList. Initialising it with
resultsList = [];
at the top of the page, and updating the same list (as opposed to reassigning it) in onSearchQuerySuccess.
function onSearchQuerySuccess(queryResults) {
resultsList.push.apply(queryResults);
$tblSearchResults.rows().invalidate().draw();
}
But this fails to re-render the table with new data. The resultsList Array is definitely getting appended to.
My Actual Question
This scenario cannot be new to this well-established technology stack.
Search form calls API to get search results. Search results are rendered in a DataTable. Doing the search again results in updated search results. Need to be updated in the table.
Maybe I am not using the appropriate terms (I am not a Javascript/JQuery developer), but I found precious little demonstrating how this should be done.