Filter not working After destroy and initialize the table

Filter not working After destroy and initialize the table

ashiquem01ashiquem01 Posts: 24Questions: 5Answers: 0
edited July 2023 in Free community support

Dear Team,

Imagine a scenario where I am adding data from a popup. Once I click the submit button, the data is saved to the database, and the datatable is destroyed. Then, I call the GetAPI to fetch the data again, and it populates correctly. However, the problem I'm facing is that the data is not being filtered as external drop down.

https://live.datatables.net/xoqaqiyu/13/edit

This question has accepted answers - jump to:

Answers

  • allanallan Posts: 61,744Questions: 1Answers: 10,111 Site admin
    Answer ✓

    Your example doesn't appear to demonstrate the issue described? It doesn't do a destroy at all.

    Might your destroy be removing the event listener on your select perhaps? Failing that, if you could update the test case to show the issue, that would be great.

    Also worth noting that you want to avoid destroying the DataTable if you can. If the new data's structure is the same as before, just use clear() and rows.add() to display the new data (or ajax.reload() if you are using ajax to load the data).

    Allan

  • ashiquem01ashiquem01 Posts: 24Questions: 5Answers: 0

    @allan Can you please check function OnSuccess(response).
    I am calling GetApi from OnSuccess after Data Added

        $(document).ready(function () {
            RetrieveDate();
        });
        function RetrieveDate()
        {
            $.ajax({
                url: "/Finance/GetAllCashbook",
                contentType: "application/json",
                dataType: 'json',
                type: "POST",
                contentType: "application/json",
                //data: JSON.stringify(filter),
                success: function (result) {
                    initializeDataTable(result.data)
                }
            });
        }
    
        function initializeDataTable(data) {
            $('#Ashique').DataTable({
                filter: true,
                "processing": true,
                "order": [[6, 'desc']],
                data: data, // Pass the new data to be displayed in the DataTable
                columns: [
                         {
                             title: "Sl No.",
                             name: "sl_no",
                             targets: 0,
                             data: "",
                             defaultContent: "",
                         },
                         {
                             title: "cashbook_id",
                             data: "cashbook_id",
                             name: "cashbook_id",
                             visible: false
                         },
                          {
                              title: "date",
                              data: "date",
                              name: "date",
                              visible: false
                          },
                         {
                             title: "Date and Time",
                             render: function (datum, type, row) {
                                 return "<div>" + row.date_ + "</div> <div style=\"font-size:12px;color:#837668\">" + row.time_ + "</div>";
                             },
                         },
                         {              
                             title: "Description",
                             render: function (datum, type, row) {
                                 return "<div>" + row.description + "</div> <div style=\"font-size:12px;color:#837668\">" + row.entry_user_name + "</div>";
                             }
                         },
                         {
                             title: "category_id",
                             data: "category_id",
                             name: "category_id",
                             visible: false
                         },
                         {
                             data: "category_name",
                             title: "Category",
                             name: "category_name",
                         },
                          {
                              title: "section_id",
                              data: "section_id",
                              name: "section_id",
                              visible: false
                          },
                         {
                             title: "Section",
                             name: "section_name",
                             data: "section_name",
                             visible: true,
                         },
                         {
                             title: "Amount",
                             render: function (datum, type, row) {
                                 if (row.cash_in_out == 1) {
                                     return "<span style='color:#2ecc71;'> " + row.cash_in + "</span>"
                                 }
                                 else {
                                     return "<span style='color:#e74c3c;'> " + row.cash_out + "</span>"
                                 }
                             },
                         },
                         {
                             title: "cash_in_out",
                             name: "cash_in_out",
                             visible: false,
                             render: function (datum, type, row) {
                                 if (row.cash_in_out == 1) {
                                     return "<span style='color:#2ecc71;'>Cash In</span>"
                                 } else {
                                     return "<span style='color:#2ecc71;'>Cash Out</span>"
                                 }
                             }
                         },
                         {
                             title: "Balance",
                             name: "balance",
                             orderable: true,
                             data: "",
                             defaultContent: ""
                         },
                         {
                             defaultContent: "",
                             render: function (datum, type, row) {
                                 var html = "";
                                 if (row.category_id != 1) {
                                     html = "<button id=\"btnEdit\" type=\"button\"  class=\"tabledit-edit-button btn btn-primary waves-effect waves-light phi-edtbtn\"><span class=\"icofont icofont-ui-edit\"></span></button>";
                                     html = html + "&nbsp; &nbsp;<button id=\"btnDelete\" type=\"button\"  class=\"tabledit-delete-button btn btn-danger waves-effect waves-light phi-dltbtn\"><span class=\"icofont icofont-ui-delete\"></span></button>";
                                 }
                                 return html;
                             }
                         },
                ],
            });
            var table1 = $('#Ashique').DataTable();
            var abc = [];
            var arratList = [];
            var RevarratList = [];
            table1.on('order.dt search.dt', function () {
                //  alert(123);
                let i = 1;
                total_cash_in = 0, total_cash_out = 0, total_balance = 0, total1 = 0;
    
                table1.cells(null, 0, { search: 'applied', order: 'applied' }).every(function (cell) {
                    this.data(i++);
                });
    
                var transactions = [];
                table1.rows({ search: 'applied', order: 'applied' }).every(function (rowIdx, tableLoop, rowLoop) {
                    var data = this.data();
                    // Build reverse array of transactions with first element being the row index
                    transactions.unshift([this.index(), data['cash_in'], data['cash_out']]);
                });
    
                let total = 0;
    
                for (i = 0; i < transactions.length; i++) {
                    data = transactions[i];
                    // console.log(data);
                    var rowIdx = data[0];
                    var credit = data[1];
                    var debit = data[2];
                    cell = table1.cell(rowIdx, 'balance:name');
                    total += credit - debit;
                    cell.data(total);
    
                    total_cash_in += credit;
                    total_cash_out += debit;
                    total_balance += total;
                }
                $("#total_cash_in").text(total_cash_in);
                $("#total_cash_out").text(total_cash_out);
                $("#total_balance").text(total);
    
            }).draw();
    
            $('#ddlFilterSection a').on('click', function () {
                table1.column('section_name:name').search($(this).text() != "All" ? $(this).text() : "").draw();
                $("#spnFilterSectionSelected").html($(this).text());
            });
            //$('#ddlFilterClass a').on('click', function () {
            //    $("#spnFilterClassSelected").html($(this).text());
            //});
            $('#ddlFilterTypes a').on('click', function () {
                table1.column('cash_in_out:name').search($(this).text() != "All" ? $(this).text() : "").draw();
                $("#spnFilterTypesSelected").html($(this).text());
            });
            $('#ddlFilterCeatedBy a').on('click', function () {
                $("#spnFilterCreatedBySelected").html($(this).text());
            });
            $('#ddlFilterCategories a').on('click', function () {
                table1.column('category_name:name').search($(this).text() != "All" ? $(this).text() : "").draw();
                $("#spnFilterCategoriesSelected").html($(this).text());
            });
            
        }
        function OnSuccess(response) {
            $('#CashbookModal').modal('hide');
            ShowCommonMsgPopup(response.data);
            var table = $('#Ashique').DataTable();
            table.destroy();
            RetrieveDate();
        }
    
  • colincolin Posts: 15,152Questions: 1Answers: 2,587

    That's a lot of code! Please can you update your test case to demonstrate the issue you want help with, that'll be easiest way for us to debug it.

    Colin

  • ashiquem01ashiquem01 Posts: 24Questions: 5Answers: 0
    edited July 2023

    Thanks, @allan The execution of ajax.reload(); is running smoothly.
    I have a question. I invoked the data table function within $(document).ready.

    In the scenario where GetAPI returns a "bad request" response, how can I handle this situation?

    Normally we use
    AjaxCOde........
    success: function (result) {
    initializeDataTable(result.data)
    }

    Now I am using below code and ajax.reload() is working finely

    $(document).ready(function () {
    var table = $('#Ashique').DataTable({
                ajax: {
                url: "/Finance/GetAllCashbook",
                contentType: "application/json",
                type: "POST",
                // "data": JSON.stringify(filter),
                "datatype": "json"
            },
            columns: [
                         {
                             title: "Sl No.",
                             name: "sl_no",
                             targets: 0,
                             data: ",
                             defaultContent: "",
                         },
                         {
                             title: "Date and Time",
                             render: function (datum, type, row) {
                                 return "<div>" + row.date_ + "</div> <div style=\"font- 
                             size:12px;color:#837668\">" + row.time_ + "</div>";
                             },
                         },
                         {
                             //data: "description",
                             title: "Description",
                             render: function (datum, type, row) {
                                 return "<div>" + row.description + "</div> <div style=\"font- 
                           size:12px;color:#837668\">" + row.entry_user_name + "</div>";
                             }
    
                         },
                 ],
    
    
      )};
    )};
    function AddSuccess(response) {
            var table22 = $('#Ashique').DataTable();
            table22.ajax.reload();
        }
    
  • kthorngrenkthorngren Posts: 20,332Questions: 26Answers: 4,774

    The 400 Bad Request is a response from the server. First start by looking at the server logs for the error to see why its responding with the 400 error. Let us know what you find.

    Kevin

  • ashiquem01ashiquem01 Posts: 24Questions: 5Answers: 0

    @kthorngren

    All functions of DataTables are working for me.
    I recently asked a question about handling AJAX calls with the success function, which is typically used to process the API response, whether it succeeds or fails. I need guidance on how to implement this in the following code.

    $(document).ready(function () {
    var table = $('#Ashique').DataTable({
                ajax: {
                url: "/Finance/GetAllCashbook",
                contentType: "application/json",
                type: "POST",
                // "data": JSON.stringify(filter),
                "datatype": "json"
            },
            columns: [
                         {
                             title: "Sl No.",
                             name: "sl_no",
                             targets: 0,
                             data: ",
                             defaultContent: "",
                         },
                         {
                             title: "Date and Time",
                             render: function (datum, type, row) {
                                 return "<div>" + row.date_ + "</div> <div style=\"font-
                             size:12px;color:#837668\">" + row.time_ + "</div>";
                             },
                         },
                         {
                             //data: "description",
                             title: "Description",
                             render: function (datum, type, row) {
                                 return "<div>" + row.description + "</div> <div style=\"font-
                           size:12px;color:#837668\">" + row.entry_user_name + "</div>";
                             }
     
                         },
                 ],
     
     
      )};
    )};
    
    
  • colincolin Posts: 15,152Questions: 1Answers: 2,587
    Answer ✓

    You can't use the success function of ajax - as the manual says:

    Must not be overridden as it is used internally in DataTables. To manipulate / transform the data returned by the server use ajax.dataSrc, or use ajax as a function.

    There are two options there, or you can use one of the events, such as xhr perhaps,

    Colin

Sign In or Register to comment.