On scroll load more data in jquery datatable using Ajax

By 19th February 2019JQuery

on scroll in a jquery datatable if you want to add more rows or data than you can use scroll methods and some ajax methods.

var processing;
    $(document).ready(function () {
var currentPageID = 1;
var from = 0;
        var to = 30;
$('.dataTables_scrollBody').on('scroll', function () {
            if (processing)
                return false;
            if ($(this).scrollTop() + $(this).innerHeight() >= ($(this)[0].scrollHeight / 2)) {
                processing = true;
                from = to + 1; // load more 30 records and will append
                to = to + 30;
                FillGrid(from, to, currentPosition); // will call for fill datatable
            }
        });





});

and here the fillgrid() method to append the 30 rows to datatable, and on sucess data will come as HTML <tr><td></td></tr> view

function FillGrid(from, to, currentPosition) {
        $.ajax({
            type: "POST",
            url: _rootURL + 'Survey/Grid',
            data: {
                "PageFrom": from,
                "PageTo": to,
            },
            success: function (data) {
                if (!$.trim(data) == '') { 
                    data = data.replace(/^\s*|\s*$/g, '');
                    data = data.replace(/\\r\\n/gm, '');
                    var expr = "</tr>\\s*<tr";
                    var regEx = new RegExp(expr, "gm");
                    var newRows = data.replace(regEx, "</tr><tr");
                    $("#SurveyDetails").DataTable().rows.add($(newRows)).draw();

                    
                    $('.dataTables_scrollBody').scrollTop(currentPosition);
                    processing = false;
                }
                else {
                    processing = true;
                }

            },
            error: function () {
                alert('error');
            }
        })
    }

Leave a Reply