How to add custom filter to ajax payload (server side processing)?

How to add custom filter to ajax payload (server side processing)?

markzzzmarkzzz Posts: 49Questions: 8Answers: 1

Hi,

I add some custom filters to my DataTable using this simple function:

function FilterRowsByColumnIntFilter(filter, columnName) {
    return $.fn.dataTable.ext.search.push(
        function (settings, data, dataIndex, originalData) {
            var selectedValue = parseInt(filter.val());
            var dataValue = parseInt(originalData[columnName]) || 0;

            return (isNaN(selectedValue) || dataValue === selectedValue);
        }
    );
}

Once I apply this filter on the interface, I see the ajax call start to the server. But where do I see this filter settings on the payload? (so I can filter on server side properly)?

Thanks for your helps

Replies

  • allanallan Posts: 63,643Questions: 1Answers: 10,492 Site admin

    Are you using server-side processing (serverSide)? If so, the client-side filtering on DataTable.ext.search will not be used at all. You need to send the filtering information to the server-side using the ajax.data function (or preXhr).

    Allan

  • markzzzmarkzzz Posts: 49Questions: 8Answers: 1
    edited March 2023

    @allan I see, thanks.

    Can this preXhr event be linked within:

    $.extend(true, $.fn.dataTable.defaults, {
        // here
    })
    

    so every call (also the first) will be triggered automatically for all DataTable I'll bind?

    I can do this:

    initComplete: function () {
        myTable.on('preXhr.dt', function (e, settings, data) {
    
        })
    }
    

    but the first call to the server will miss the filter settings...

  • kthorngrenkthorngren Posts: 21,418Questions: 26Answers: 4,968

    The way to use preXhr is to define it like the example in the docs:

    $('#example')
        .on('preXhr.dt', function ( e, settings, data ) {
            data.sessionId = $('#sessionId').val();
        } )
        .dataTable( {
            ajax: "data.json"
        } );
    

    This way its bound before Datatables initializes.

    Kevin

  • markzzzmarkzzz Posts: 49Questions: 8Answers: 1

    Thanks to everybody!

Sign In or Register to comment.