How to update JQuery DataTable when clicking on button?

How to update JQuery DataTable when clicking on button?

MilyMily Posts: 15Questions: 3Answers: 0

Link to test case: No test case likn because of the code complexity
Debugger code (debug.datatables.net):
Description of problem:
Dear all,
When I update my Data Table :smile:

I can't do it because I have the following message error:
DataTables warning: table id=tableServerSide - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3

Here is my code:

@model ClientSelectionViewModel

@{
    ViewBag.Title = "Sélection des clients";
}

<link href="~/lib/datatables/css/dataTables.bootstrap4.min.css" rel="stylesheet" />

<h3><i class="fas fa-clipboard-list mr-3"></i> Sélection des clients</h3>
<div asp-validation-summary="All" class="text-danger mt-2"></div>

<div id="filters">
    <form method="post" asp-action="facturationWithFilters">
        <div class="input-group form-group">
            ...
        </div>
        <div class="input-group form-group">
            ...
            <select id="contractFilter" name="ContractTypes" class="form-control selectpicker" multiple="multiple" placeholder="Types de contrat"
                    title="Filtrer par type de contrat" data-style="border text-secondary"
                    value="@Model.Type">
               ...
            </select>
        </div>
        <div class="input-group form-group">
            <div class="input-group-prepend">
                ...
            </div>
            <select id="paymentFilter" name="PaymentChoices" class="form-control selectpicker" multiple="multiple" placeholder="Moyen de paiement"
                    title="Filtrer par moyen de payement" data-style="border text-secondary"
                    value="@Model.P">
                ...
            </select>
        </div>
        <div class="input-group form-group">
            <div class="input-group-prepend">
               ...
            </div>
            <select id="populationFilter" name="PopulationTypes" class="form-control selectpicker" multiple="multiple" placeholder="Population"
                    title="Filtrer par population" data-style="border text-secondary"
                    value="@Model.S">
                ...
            </select>
        </div>

    </form>
    <button id="btn-filter-clients" class="btn atmb-btn-blue"><i class="fas fa-filter fa-fw mr-2"></i>Filtrer les clients</button>

</div>

    <div id="client-selection" type="hidden" class="mt-2">

        <div class="mb-1">
            <a id="btn-send-selection" class="btn float-right atmb-btn-red">
                <i class="fas fa-feather-alt fa-fw mr-2"></i>Lancer la facturation pour les utilisateurs sélectionnés
            </a>
        </div>

        <table class="table table-striped table-hover table-sm table-bordered"
               id="tableServerSide"
               style="width:100%;">
            <thead class="thead-dark text-white">
                <tr>
                    <th>Check</th>
                    <th>Number</th>
                    <th>Types</th>
                    <th>Payment</th>
                    <th>Population</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>

<table id="test"></table>

@section Scripts {

    <!--scripts DataTable-->
    <script src="~/js/modal.js"></script>
    <script src="~/lib/datatables/js/jquery.dataTables.min.js"></script>
    <script src="~/lib/datatables/js/dataTables.bootstrap4.min.js"></script>

    <!--script pour la gestion de DataTable-->
    <script type="text/javascript">

        $("#client-selection").hide();

        //--------------------
        // Filter selection
        //--------------------
        $('#btn-filter-clients').click(function () {
            $("#client-selection").show();

            $.support.cors = true;

            var filters = {
                ContractTypes: $("#contractFilter").val().join(','),
                PaymentChoices: $("#paymentFilter").val().join(','),
                PopulationTypes: $("#populationFilter").val().join(','),
                StrictFilteringContractTypes: $("#StrictFilteringContractTypes").is(":checked")
            }

                $("#tableServerSide").DataTable({
                    "processing": true,
                    "serverSide": true,  
                    "filter": true,
                    "ajax": { 
                        "url": "@Url.Action("AjaxPostCall", "ClientSelection")",
                        "type": "POST",
                        "data": filters,
                        "datatype": "json"
                    },
                    "columns": [ 
                        {
                            "data": null,
                            "className": "col-checkbox",
                            "render": function (data, type, row) {
                                var checkId = 'check' + row.id;
                                var isChecked = selectedIds.includes(checkId) ? ' checked="checked"' : '';
                                var checkbox = '<input id="' + checkId + '" type="checkbox" '
                                    + isChecked
                                    + ' class="server-checkbox" /> ';

                                return checkbox;
                            }
                        },
                        {
                            "data": "id",
                            "className": "col-id"
                        },
                        {
                            "data": "contractsTypes",
                            "className": "col-contractstypes"
                        },
                        {
                            "data": "paymentChoice",
                            "className": "col-paymentchoice"
                        },
                        {
                            "data": "populationType",
                            "className": "col-populationtype"
                        }
                    ]
                });

        });
    
    </script>
 }

Can you please tell me how to fix it?
Thanks :)

This question has an accepted answers - jump to answer

Answers

  • tangerinetangerine Posts: 3,365Questions: 39Answers: 395

    You are initialising your DataTable inside a click function; each click after the first one means trying to re-initialise an existing table, which DT does not allow.

  • MilyMily Posts: 15Questions: 3Answers: 0

    Ok :( so do you have any idea on how to solve it?
    Thanks for your reply :)

  • colincolin Posts: 15,240Questions: 1Answers: 2,599
    Answer ✓

    You could call $.fn.dataTable.isDataTable(), and check and see whether it is a DataTables before initialising again,

    Colin

  • MilyMily Posts: 15Questions: 3Answers: 0

    Never give up! :) I've used the following solution which worked for me:

    //Check if datatable instance exists before ajax starts:
    if ($.fn.dataTable.isDataTable('#dtid')) {
        $('#dtid').dataTable().fnDestroy();               
    }
    
    //reintialise after ajax success:
    $('#dtid').DataTable({
    

    Have a nice evening :)

  • MilyMily Posts: 15Questions: 3Answers: 0

    Thanks Colin for your answer :)

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    You're welcome, glad all sorted,

    Colin

This discussion has been closed.