Search code examples
javascriptjqueryrazorrazor-pages

error Datable id=example can't reinitialize data table?


I work on razor page asp.net core . I face error Datable id=example can't reinitialize data table ?

so How to solve this error please ?

error happen when change select option printer server

I need when change select on select option printer server then hide or remove table with pagination option first ,next,previous,last etc

 <script type="text/javascript">
        $(document).ready(function () {
     
            
           
        
            $('#PrintServer-select').change(function () {
                var printserverId = $(this).val();
               
                if (printserverId) {
                    console.log(printserverId);
                    $.ajax({
         
                        url: '?handler=RelatedBranches',
                        type: "GET",
                        dataType: "json",

                        data: { printserverId: printserverId },
                        success: function (data) {
                            console.log(data);
                            $('#branch-select').empty();
                            $.each(data, function (i, item) {
                                //console.log(item);
                                $('#branch-select').append($('<option>', {
                                    
                                    value: item.branchId,
                                    text: item.vBranchDesc
                                    
                                    
                                }));
                            });
                   
                            var tableShows = $('#example').DataTable({
                                paging: false
                            });

                            // Hide the table using jQuery
                            $('#example').hide();
                  
                            $('#example').DataTable();
                            if ($.fn.dataTable.isDataTable('#example')) {
                                $('#example').destory();
                                // The DataTables instance is already initialized
                            } else {
                                // Initialize the DataTables plugin
                                $('#example').DataTable();
                            }
                        }
                    });
                }
            });
            
           
            var table = $("#example").dataTable({
                "bFilter": false,
                "bSort": false,
                "paging": true,
                "bPaginate": true,
                "pagingType": "full_numbers",
                
                "columnDefs": [
                    { className: "pad-md-left-p-10 pad-top-bottom-p-10", "targets": [0, 1, 2, 3, 4, 5, 6, 7] }
                ],
                "lengthMenu": [[5,10, 15,20, 25, 35, 50, 100, -1], [5,10, 15,20, 25, 35, 50, 100, "All"]],
                "pageLength": 10 // Set the default page length to 10
            });
        
            

           
           
            table.destroy();

            
          
         
         

          

        });
    </script>

error happen on block below

 var tableShows = $('#example').DataTable({
                                    paging: false
                                });
    
                                // Hide the table using jQuery
                                $('#example').hide();
                     
                                $('#example').DataTable();
                                if ($.fn.dataTable.isDataTable('#example')) {
                                    $('#example').destory();
                                    // The DataTables instance is already initialized
                                } else {
                                    // Initialize the DataTables plugin
                                    $('#example').DataTable();
                                }

image for what i need datatable remove


Solution

  • I try below and it success solve my issue

    Try this

    $(document).ready(function () {
        // Create a variable to store the DataTable instance
        var table;
    
        $('#PrintServer-select').change(function () {
            var printserverId = $(this).val();
            if (printserverId) {
                console.log(printserverId);
                $.ajax({
                    url: '',
                    type: "GET",
                    dataType: "json",
                    data: { printserverId: printserverId },
                    success: function (data) {
                        console.log(data);
                        $('#branch-select').empty();
                        $.each(data, function (i, item) {
                            $('#branch-select').append($('<option>', {
                                value: item.branchId,
                                text: item.vBranchDesc
                            }));
                        });
    
                        // Destroy the existing DataTable instance if it exists
                        if (table && $.fn.DataTable.isDataTable('#example')) {
                            table.destroy();
                        }
    
                        // Hide the table using jQuery
                        $('#example').hide();
    
                        // Reinitialize the DataTable
                        table = $('#example').DataTable({
                            paging: false
                        });
                    }
                });
            }
        });
    
        // Initialize the DataTable outside of the change event
        table = $("#example").DataTable({
            "bFilter": false,
            "bSort": false,
            "paging": true,
            "bPaginate": true,
            "pagingType": "full_numbers",
            "columnDefs": [
                { className: "pad-md-left-p-10 pad-top-bottom-p-10", "targets": [0, 1, 2, 3, 4, 5, 6, 7] }
            ],
            "lengthMenu": [[5, 10, 15, 20, 25, 35, 50, 100, -1], [5, 10, 15, 20, 25, 35, 50, 100, "All"]],
            "pageLength": 10 // Set the default page length to 10
        });
    
        // Optional: Destroy the DataTable instance on document unload to prevent memory leaks
        $(window).on('beforeunload', function () {
            if (table && $.fn.DataTable.isDataTable('#example')) {
                table.destroy();
            }
        });
    });
    

    Aside from the fact that you can't consistently spell "destroy" between two different calls, and the fact that you're trying to call that method directly on the jQuery object rather than calling it properly as shown

    Even five minutes walking through your code with the debugger would have shown you that you:

    1-Create the table

    2- Immediately try to destroy the table, but fail because you've not called the method correctly

    3-Create the table

    4- Create the table again

    5-Immediately try to destroy the table, but fail because you've not called the method correctly, and this time you can't even spell it properly

    And between all of that, you're not making any changes to the table at all, so the repeated calls to create and destroy it make absolutely no sense.