Why my jquery datatable shows data at first attempt but not for the subsequent attempt?

試著忘記壹切 提交于 2020-01-06 07:24:02

问题


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("");
        }
    });
}

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/53390601/why-my-jquery-datatable-shows-data-at-first-attempt-but-not-for-the-subsequent-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!