Empty table filled by search button (ajax) with paging - Bootstrap 4

Empty table filled by search button (ajax) with paging - Bootstrap 4

BevanBevan Posts: 4Questions: 2Answers: 0

Good morning.
A little stuck. We have a current implementation shown below using the old version of DataTables.
The page has a number of entries a user can choose from and then click 'Search'.
The createTable() function calls a web service with the combined search criteria and paging/search information.
On return, a .dataTable() is created an returned to the screen.

Issues:
1) old implementation, would like to switch to .ajax
2) because the #tbl isn't instantiated as a .DataTable on page load, Bootstrap 4 css is not applied correctly

Really smart folks on this forum. Any help would be greatly appreciated.

Current implementation

<!--html-->
<!-- numerous searching criteria -->
<input type="button" id="SearchButton" class="btn btn-success btn-sm" value="Search" />
<table id="tbl" class="table table-bordered table-condensed table-striped table-hover"></table>

<!--script-->
$('#SearchButton').on('click', function () {
     createTable();
});

// Paged Table Functions
function getTableData(page, sortColumn, sortDirection) {
        var dfd = $.Deferred();
        var pageSize = $('[name=tbl_length]').val();
        var search = $('#tbl_filter label input').val() ? $('#tbl_filter label input').val() : null;
        var startdate = $('#StartDate').val() === '' ? '1/1/1900' : $('#StartDate').val();
        var enddate = $('#EndDate').val() === '' ? '1/1/3000' : $('#EndDate').val();

        var data = {
            FacilityId: $('#FacilityId').val(),
            UserId: $('#UserId').val(),
            RequestedBy: $('#ProfileUserId').val(),
            StartDate: startdate,
            EndDate: enddate,
            Keyword: $('#Keyword').val()
        };

        var searchParams = {
            Search: search,
            Page: page,
            PageSize: pageSize,
            SortColumn: sortColumn,
            SortDirection: sortDirection
        }

        $.extend(data, searchParams);

        $.ajax(url, {
            type: 'Post',
            data: JSON.stringify(data),
            dataType: 'text',
            contentType: null,
            cache: false,
            success: function (result) {
                try {
                    dfd.resolve(JSON.parse(result));
                } catch (ex) {
                    dfd.resolve(result);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                dfd.reject(jqXHR, textStatus, errorThrown);
            }
        });

        return dfd.promise();
}

function createTable() {
        var entryId;

        var optionalSettings = {};

        var columns =
            [
                { title: 'No.', data: 'Number', render: function (data, type, row) { return '<a href="/Main/Controller/View/' + row.EntryId 
                        + '">' + data + '</a>' } },
                { title: 'Name', data: 'Name', 'class': 'text-nowrap', render: function (data) { return data } },
                { title: 'Date', data: 'Date', 'class': 'text-center', render: function (data) { return data } },
                { title: 'Location', data: 'Location', 'class': 'text-nowrap', render: function (data) { return data } },
        ];

        createPagedTable('#tbl', columns, optionalSettings, 3, 'desc', getTableData);

}

function createPagedTable(selector, columns, optionalSettings, sortColumnIndex, sortDirection, fnGetData) {

        if (!sortColumnIndex) sortColumnIndex = 0;
        if (!sortDirection) sortDirection = 'asc';

        var tableSettings = {
            "dom": 'Rlfrtip',
            "processing": true,
            "serverSide": true,
            "language": {
                "infoFiltered": ""
            },
            "fnDrawCallback": function () {
                $("[rel='tooltip']").tooltip();
            }
        }

        // Optional Settings
        $.extend(tableSettings, optionalSettings || {});

        // Add Columns
        $.extend(tableSettings, {
            "order": [[sortColumnIndex, sortDirection]],
            "aoColumns" : columns
        });

        // Add Get Data Function
        $.extend(tableSettings, {
            "fnServerData": function (sSource, aoData, fnCallback) {
                var page = aoData[3].value;
                var sortColumn = columns[aoData[2].value[0].column].mData;
                var sortDirection = aoData[2].value[0].dir;

                fnGetData(page, sortColumn, sortDirection).then(function (data) {
                    fnCallback({
                        "iTotalRecords": data.length < 1 ? 0 : data[0].TotalRows,
                        "iTotalDisplayRecords": data.length < 1 ? 0 : data[0].FilteredTotalRows,
                        "aaData": data
                    });
                });
            }
        });

        if (!$.fn.DataTable.isDataTable(selector)) {
            pagedTable = $(selector).dataTable(tableSettings);
        } else {
            pagedTable.fnDraw();
        }

        return pagedTable;
}

Answers

  • allanallan Posts: 47,517Questions: 1Answers: 6,755 Site admin

    Its this:

    "dom": 'Rlfrtip',
    

    For Bootstrap it needs to be significantly more complex than that I'm afraid. The dom documentation shows the Bootstrap 4 default - I'd suggest using that as the basis for your modifications.

    Allan

  • BevanBevan Posts: 4Questions: 2Answers: 0

    Thank you very much, instantly corrected the issue. Always the simplest item that is overlooked.
    I've tried to convert this to the new 1.10 ajax configuration, but receive numerous errors. I could not find any definitive guides for the conversion.

    Simple example: (from website)

    $('#example').dataTable( {
      "ajax": function (data, callback, settings) {
        callback(
          JSON.parse( localStorage.getItem('dataTablesData') )
        );
      }
    } );
    
    "fnServerData": function (sSource, aoData, fnCallback) {
                    var page = aoData[3].value;
                    var sortColumn = columns[aoData[2].value[0].column].mData;
                    var sortDirection = aoData[2].value[0].dir;
     
                    fnGetData(page, sortColumn, sortDirection).then(function (data) {
                        fnCallback({
                            "iTotalRecords": data.length < 1 ? 0 : data[0].TotalRows,
                            "iTotalDisplayRecords": data.length < 1 ? 0 : data[0].FilteredTotalRows,
                            "aaData": data
                        });
                    });
                }
    
  • allanallan Posts: 47,517Questions: 1Answers: 6,755 Site admin

    I'm not sure that dom has even been described as simple! I'm actually working on a replacement for it at the moment.

    Rather than using ajax for loading data from localStorage, I'd probably just use data:

    data: JSON.parse( localStorage.getItem('dataTablesData') )
    

    Allan

  • allanallan Posts: 47,517Questions: 1Answers: 6,755 Site admin

    It should probably check that there is a dataTablesData property before calling that, and if not, just insert an empty array.

    Allan

Sign In or Register to comment.