Peter
Peter

Reputation: 9113

Passing the total row count to Datatables

I've got a datatables implementation that does an ajax request tho $_SERVER['PHP_SELF']. I run my query to get all records when the page loads. However, the first ajax call will do this again without limit. I was wondering if it is possible to pass the total row count in the initial ajax request. This is my datatables code:

var myTable = $('.datatable').DataTable({
    "serverSide": true,
    "processing": true,
    "paging": true,
    "searching": { "regex": true },
    "lengthMenu": [ [10, 25, 50, 100, -1], [10, 25, 50, 100, "All"] ],
    "pageLength": 10,
    "ajax": {
        "type": "POST",
        "url": "<?= $_SERVER['PHP_SELF']; ?>",
        "dataType": "json",
        "contentType": 'application/json; charset=utf-8',
        "data": function (data) {
            // Grab form values containing user options
            var form = {};
            $.each($("form").serializeArray(), function (i, field) {
                form[field.name] = field.value || "";
            });
            // Add options used by Datatables
            var info = { "start": 0, "length": 10, "draw": 1 };
            $.extend(form, info);
            return JSON.stringify(form);
        },
        "complete": function(response) {
            console.log(response);
       }
    }
});

Upvotes: 1

Views: 2673

Answers (1)

Peter
Peter

Reputation: 9113

I've found the solution to my issue which in terms seemed to be multiple issues.

  1. I had the wrong value for recordsTotal thinking it was supposed to be the amount of rows I wanted to retrieve in my ajax call.

  2. "contentType": 'application/json; charset=utf-8', seemed to break my ajax request.

  3. I now pass the total number of rows using:

    "data": { "totalRows": "", },

  4. I now set $totalData initially using a count on my query results and then overwriting it using $_REQUEST.

Upvotes: 1

Related Questions