How to get recordsTotal from response header

How to get recordsTotal from response header

amir manianamir manian Posts: 2Questions: 1Answers: 0
edited March 2017 in Free community support

Hi!
I'm using ajax request to fill dataTable. The API returns totalcount in "Response header" (I can't change the api).How can I reach response header to get totalcount in ajax call

$('#' + tableId).DataTable({
            serverSide: true,
            processing: true,
            ajax: {
                url: myUrl,
                data: function (d) {
                    var pageIndex = d.start / d.length;
                    var pageSize = d.length;
                    var sortCol = columns[d.order[0].column].data; // Get column name from column index
                    var sort = sortCol + ',' + d.order[0].dir; // API sort format : "colName,direction"
                    var searchValue = d.search.value;
                    return $.extend({}, "", {
                        "page": pageIndex,
                        "size": pageSize,
                        "sort": sort,
                        "search": searchValue
                    });
                },
                async: false,
                type: 'GET',
                headers: {
                    'Authorization': authorization
                },
                dataFilter: function (data) { // Rename json props to satisfy datatable expectations.
                    var json = {};
                    json.recordsTotal = 26; // **responseHeader.total**
                    json.recordsFiltered = 26; // **responseHeader.total**
                    json.data = jQuery.parseJSON(data); // data.result
                    return JSON.stringify(json); // return JSON string
                },

Answers

  • amir manianamir manian Posts: 2Questions: 1Answers: 0

    The xhr.dt event worked for me. don't forget to use async: true on your ajax.

    $('#' + tableId)
            .on('xhr.dt', function (e, settings, json, xhr) {
                json.recordsTotal = json.recordsFiltered = xhr.getResponseHeader('count header name here');
                // Note no return - manipulate the data directly in the JSON object.
            })
            .DataTable({
                serverSide: true,
                processing: true,
                ajax: {
                    url: baseApiUrl + relativeUrl,
                    async: true,
                   ...
                }
    
Sign In or Register to comment.