0

I am using Datatables plugin with server-side processing. My table is initiated on a button press. I want to apply a filter to couple of columns on the table when it is actually initialized. I tried using searchCols, but no result. My code is as follows:

var table = dataTables.create("#projectTable", parameters, {
                        ajax: {
                            url: 'project/search.do',
                            data: function(d) {
                                d.numberOfColumns = 6
                                d.startDate = jQuery("#start").val(),
                                d.endDate = jQuery("#end").val()                            
                            },
                            dataSrc: "rows",
                            type: 'GET'
                        },
                        columns: getColumns(),
                        "columnDefs": getColumnDefs(),                          
                        searchCols: [
                                       null,
                                       { sSearch: jQuery("#selectBox1").val() },                                       
                                       { sSearch: jQuery("#selectBox2").val() },
                                       null,
                                       null,
                                       null
                                     ]
                    });
                }

For now, I am using the column.search.draw() which is making the table to load again ruining the performance of my application. Any help is appreciated!

5
  • maybe it should be search instead of sSearch? Unless this is an older version or something Commented Feb 14, 2017 at 23:25
  • Thanks for the reply A. Lau. I tried search first. Later found this : datatables.net/forums/discussion/21087/… Commented Feb 14, 2017 at 23:38
  • I have a table that I initialize empty then wait for the user to click on a button to grab the search criteria and make the ajax call. I do this using the deferLoading property. Commented Feb 15, 2017 at 1:55
  • @Bindrid do you mind sharing the code? Thank you. Commented Feb 15, 2017 at 14:43
  • I will put it up in a couple of hours when I get to work Commented Feb 15, 2017 at 14:45

2 Answers 2

2

My table definitions are placed in functions to be used on multiple tables in multiple tabs as shown below. Some of the more irrelevant code has been removed.

  ClientInterface.getDataTableDefinition = function (me) {


        var wspath = getBasePath("ws/wsClient.asmx/GetClientInterfaceLabels");

        var options = {

            sorting: false,
            paging: false,
            searching: false,
            language:{emptyTable: 'Select a Fiscal year and Activity then click "Go"'},
            columnDefs: [{
                targets: [1, 2], render: function (data, type, full, meta) {
                    // Make the html table editable
                    return "<div contenteditable='true'>" + data + "</div>"
                }
            }],

            select: false,
            dom: 'lfrtB',
            columns: [{ 'data': 'DefaultLabel' },
                { 'data': 'AssignedLabel' },
                { 'data': 'ToolTip' }],

            serverSide: true,
            ajax: {
                url: wspath,
                type: "POST",
                contentType: "application/json; charset=utf-8",
                data: function (ssp) {
                    // button click is used to verify something has been selected so it
                    // is blindly fetched here.
                    var actid = $("#ddlActivity").val();
                    var fy = $("#ddlFiscalYear").val();
                    me.lastLabelFetch = { ActId: actid, FiscalYear: fy };
                    return JSON.stringify({ ActId: actid, FiscalYear: fy });
                },
                error: function (response) { onAjaxError(response) },
                dataFilter: function (data) {

                    // the web method returns the data in a wrapper 
                    // so it has to be pulled out and put in the 
                    // form that DataTables is expecting.
                    var p = JSON.parse(data);
                    // set tr id based on row id and tab number.
                    //  $.map(p.d.data, function (val, i) { val.trid = prepend + val.rowId; });
                    var d = JSON.parse(p.d);
                    //  me._$tblMyDataTable.select.style(p.d.length > 0);
                    return JSON.stringify({ data: d });
                }
            },
            // Data Table is not loaded until the user selects Activity and Fiscal Year.
            deferLoading: 0,

            initComplete: function () {

            }

        }
        return options;
    };

This is my event handler. It makes sure that the two values from a selectbox are valid. If they are, then the datatable load is triggered.

    ClientInterfaceLabels.prototype.onBtnGoClicked = function () {

        var me = this;
        var activityId = $("#ddlActivity").val();
        var fiscalYear = $("#ddlFiscalYear").val();


        var msg = "";
        // validate inputs and show modal message if missing

        if (activityId == "0") { msg += "<h3>Activity.</h3>"; };
        if (fiscalYear == "0") { msg += "<h3>Fiscal year.</h3>"; };

        if (msg.length > 0) {
            msg = "<h2>Please provide the following:</h2>" + msg;
            clientBased.alert({ message: msg });
            return;
        }   
        this._$tblDataTableLables.ajax.reload();

    };

And the actual table, button and select box initialization:

    ClientInterfaceLabels.prototype.initialize= function () {

        var me = this;

        $("#ButtonGo").button().click(function () { me.onBtnGoClicked(); });
        $("#ddlFiscalYear").select2();
        $("#ddlActivity").select2();

        this._$tblHtmlLabels = $("#tblLabels");
        this._$tblDataTableLables = this._$tblHtmlLabels.DataTable(ClientInterfaceLabels.getDataTableDefinition(me));
    }

What they see when the first load the page

What the see after selecting items and clicking go

Sign up to request clarification or add additional context in comments.

5 Comments

Notice deferLoading, just by being there, ajax is deferred until the user click on the go button. The integer is used to calculate paging if paging is turned on. (in my case it is not so I set it to 0)
When I try pressing the button for the second time, it gave me a cannot re-initalize error. Do you have any idea why?
yes, you are reinitializing the table. The table should be initialized on page load as an empty table then use the button click the trigger the ajax
I was not able to initialize an empty table. That is the reason why I made something like that.
I added pictures of what they see when the load the page, and what they see after clicking go. Also, my comment about the language attribute was wrong so I fixed it and put it in the code above
0

There is one other thing you can do in your button handler that might help:

$("#btnGo").on("click", function() {
     if($.fn.dataTable.isDataTable("#tbl")) {
         $("#tbl").DataTable().ajax.reload();
     }
     else {
          $("#tbl").DataTable(tableDef);
     }

 } )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.