Why my jquery datatable shows data at first attemp

2019-09-05 21:18发布

I am using this to load a table but it works when I load it for the first time i.e. first request but on the subsequent request it fails to load the new data.

I am using asp.net mvc with jquery datatable. Why Doesn't it work?

THrows this error in console.

I am getting "Cannot read property 'reload' of undefined"

$('form').submit(function(e) {
    e.preventDefault();
    if (!$(this).valid()) {
        $("#tbodytblServicesReport").html("");
        return;
    } else {
        filltblServicesReport();
    }
});

function filltblServicesReport() {

    $('tfoot td#tdTotal').text("");
    var url = '@Url.Action("ServicesDetailedReportPartyWise")';
    var data = {
        FromDate: $("#FromDate").val(),
        ToDate: $("#ToDate").val(),
        PartyName: $("#PartyName").val()
    }
    $.post(url, data, function(response) {
        if (response.ReturnStatusJSON == true) {
            $("#tbodytblServicesReport").html("");
            var counter = 1;
            $.each(response.lstDetailedServicesReturned, function(i, val) {
                $("#tbodytblServicesReport").append($('<tr>').append($('<td>').html(i))
                    .append($('<td>').html((val.EntryDateTime === null || val.EntryDateTime === "") ? "N/A" : formatJSONDate(val.EntryDateTime)))
                    .append($('<td>').html(val.InvoiceNo))
                    .append($('<td>').html(val.CustomerName))
                    .append($('<td>').html(val.VehicleRegNo))
                    .append($('<td>').html(val.ServiceName))
                    .append($('<td>').html(val.PartyName))
                    .append($('<td>').html(val.ServicePrice))
                    .append($('<td>').html(val.Commission))
                )
                i++;
                $('tfoot td#tdTotal').text(val.TotalCost);
                $('tfoot td#tdTotalCommission').text(val.TotalCommission);
                $('tfoot td#tdCommissionValue').text("-" + val.TotalCommission);
                $('tfoot td#tdFinalTotal').text(val.TotalCostMinusTotalCommission);
                //$('tfoot td#tdTotalCostMinusCommissionMinusTotalOtherExpenses').text(val.TotalCostMinusCommissionMinusTotalOtherExpenses);
                counter = i;
            })

            if (counter <= 1) {
                $('tfoot td#tdTotal').text("");
                $('tfoot td#tdTotalCommission').text("");
                $('tfoot td#tdCommissionValue').text("");
                $('tfoot td#tdFinalTotal').text("");
                //$('tfoot td#tdTotalCostMinusCommissionMinusTotalOtherExpenses').text("");
                return;
            }

            $('#tblServicesReport').show();

            $('#tblServicesReport').DataTable.ajax.reload(null, false)({
                bPaginate: false,
                dom: 'Bfrtip',
                buttons: [
                    'copyHtml5',
                    'excelHtml5',
                    'csvHtml5',
                    {
                        extend: 'pdfHtml5',
                        footer: true,
                        title: 'Party Wise Report (' + $('#FromDate').val() + ' - ' + $('#ToDate').val() + ')',
                        customize: function(doc) {
                            doc.styles.title = {
                                color: 'gray',
                                fontSize: '15',
                                alignment: 'center'
                            }
                            doc.content[1].table.widths = Array(doc.content[1].table.body[0].length + 1).join('*').split('');
                            doc.styles.tableHeader.fontSize = 10;
                            doc.styles.tableHeader.alignment = 'left';
                            doc.styles.tableHeader.color = 'white'
                        }
                    },
                    {
                        extend: 'print',
                        footer: true
                        //title: 'Sales Report'
                    }
                ]
            });
        } else {
            swal("Sorry !", "No Record Found", "error");
            $("#tbodytblServicesReport").html("");
        }
    });
}

2条回答
地球回转人心会变
2楼-- · 2019-09-05 22:03

Datatable has built-in ajax, so initialise your table as this

var url = '@Url.Action("ServicesDetailedReportPartyWise")';
var data = {
    FromDate: $("#FromDate").val(),
    ToDate: $("#ToDate").val(),
    PartyName: $("#PartyName").val()
}
var myTable = $('#tblServicesReport').DataTable({ ajax: url });

and you can reload with myTable.ajax.reload(); on desired event

IMO, refactore your code to do better split between structure creation and data populate with logical as described in my example.

查看更多
再贱就再见
3楼-- · 2019-09-05 22:10

reload method of a table won't work, so there's a way around of how you do it.

first the initial load is proper then for other loads after that needs to destroy the datatable and empty the rows so here how I did it -

Create datatable for 1st TIME

$('#mytable').dataTable()

for the second time : -

//ajax for delete row
    $.ajax({
                    url: url,
                    type: "POST",
                    data: { request },
                    cache: false,
                    success: function (data) {

                            //DESTROY datatable
                            $('#mytable').DataTable().destroy();

                            //remove table rows
                            $('#mytable tbody').empty();
                            $.ajax({
                                type: "GET",
                                url: "url",
                                "columnDefs": [
                            { className: "ques", "targets": [1] }
                                ],
                                success: function (response) {

                                    if (response.Status === 1) {
                                     //Create new table and get list
                                        $('#mytable').dataTable({
                                            "data": response.data,
                                            "initComplete": function (settings, json) {
                                                App.unblockUI('.questionslist');
                                            },
                                            columns: [{ "data": "Id" },
                                            { "data": "Question", "width": "50%" },

                                            { "data": null, "render": function (data, type, full) { return '<a class="btn btn-info btn-sm" href=/Home/EditQuestion/' + full.Id + '>' + 'Edit' + '</a>'; }, },
                                            { "data": null, "render": function (data, type, row) { return '<button type="button" class="btn btn-danger btn-sm" value="' + row.Id + '" id="delete">DELETE</button>' } }
                                            ],
                                            "pageLength": 10,
                                            "order": [[0, "desc"]],
                                        });
                                    } else {

                                        toastr.error(response.Message)
                                    }
                                },
                                failure: function (response) {
                                },
                                error: function (response) {

                                }
                            });
                        }
                        else {
                        }
                    },
                    error: function (ex) {
                    },
                })

for those who didn't understand 1st ajax call here does a DELETE method : - deletes a row from datatable

IF successfully deleted, it destroys the datatable and removes all rows

                    //DESTROY datatable
                    $('#mytable').DataTable().destroy();

                    //remove table rows
                    $('#mytable tbody').empty();

AFTER THAT the final ajax call gets all the table's data again (after deleting one entry), and loads it into the table

^^^^ in the above ajax call, after destroying the datatable it looks as a new table ,hence it will work similarly as it worked for the first time

revert if any doubt

查看更多
登录 后发表回答