Trying to reload datatable once checkbox is clicked

Trying to reload datatable once checkbox is clicked

Katrell01Katrell01 Posts: 8Questions: 2Answers: 0
edited July 2019 in Free community support

I am trying to reload my datatable once I click my checkbox but I continue you receive error :datatables.min.js:64 Uncaught TypeError: Cannot set property 'data' of null

Code:

Javascript:

function ReloadTable()
{


    $(document).ready(function () {
        var table =  $('#DashboardTable').DataTable({

            "processing": true, // for show progress bar
            "serverSide": true, // for process server side
            "filter": true, // this is for disable filter (search box)
            "orderMulti": false, // for disable multiple column at once
            "ajax": {
                "url": "/Chargeback/Index",
                "type": "GET",
                "datatype": "json"
            },
            "columns": [
            { "data": "ChargebackCode", "name":"Code" },
            { "data": "StatusName", "name":"Status" },
            { "data": "BusinessUnitName", "name":"Business" },
            { "data": "InvoiceCode", "name":"Invoice" },
            { "data": "OrderCode", "name":"Order"},
            { "data": "PickTicketCode", "name":"Pick Tickets" },
            { "data": "CustomerPo", "name":"Customer PO" },
            { "data": "AssignedDepartment","name": "Assigned"},
            { "data": "DivisionName", "name":"Division"},
            { "data": "Customer", "name":"Customer" },
            { "data": "WarehouseName","name": "Warehouse" },
            { "data": "Coordinator","name": "Coordinator" },
            { "data": "ChargebackDate","name": "Open Date" },
            { "data": "ModDate", "name":"Last Activity" },
            { "data": "ChargebackDeadline", "name": "Deadline" },
            { "data": "ChargebackCloseDate", "name": "Closed Date" },
            { "data": " DaysOpen", "name": "Days Open" },
            { "data": "ChargebackAmount", "name": "Amount" },
            { "data": "ChargebackBalance", "name": "Balance" },
            { "data": "FaultName", "name": "Fault" },
            { "data": "ResponsibleName", "name": "Responsible" }
            ]
        });
        //console.trace("Our first Trace");
        table.ajax.reload();
    });

}

View:

@using (Html.BeginForm("Index", "Chargeback"))
{
   <label id = "Include" > @Html.CheckBox("IncludeClosed", (bool)ViewBag.IncludeClosed, new { onChange = "ReloadTable()" }) Include Closed</label>

<table id="DashboardTable" class="table table-striped" >
    <thead>
        <tr>
            <th>Code</th>
            <th>Status</th>
            <th>Business</th>
            <th>Invoice</th>
            <th>Order</th>
            <th>Pick Tickets</th>
            <th>Customer PO</th>
            <th>Assigned</th>
            <th>Division</th>
            <th>Customer</th>
            <th>Warehouse</th>
            <th>Coordinator</th>
            <th>Open Date</th>
            <th>Last Activity</th>
            <th>Deadline</th>
            <th>Closed Date</th>
            <th>Days Open</th>
            <th>Amount</th>
            <th>Balance</th>
            <th>Fault</th>
            <th>Responsible</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            var chargebackDeadline = item.ChargebackDeadline == null ? "" : ((DateTime)item.ChargebackDeadline).ToString("MM/dd/yyyy");
            var chargebackCloseDateAsString = item.ChargebackCloseDate == null ? "" : ((DateTime)item.ChargebackCloseDate).ToString("MM/dd/yyyy");

            <tr>
                <td>@Html.ActionLink(item.ChargebackCode, "Details", "Chargeback", new { id = item.Id }, null)</td>
                <td>@item.StatusName</td>
                <td>@item.BusinessUnitName</td>
                <td>@item.InvoiceCode</td>
                <td>@item.OrderCode</td>
                <td>@item.PickTicketCode</td>
                <td>@item.CustomerPo</td>
                <td>@item.AssignedDepartment</td>
                <td>@item.DivisionName</td>
                <td>@item.Customer</td>
                <td>@item.WarehouseName</td>
                <td>@item.Coordinator</td>
                <td>@item.ChargebackDate.ToString("MM/dd/yyyy")</td>
                <td>@item.ModDate.ToString("MM/dd/yyyy")</td>
                <td>@chargebackDeadline</td>
                <td>@chargebackCloseDateAsString</td>
                <td>@item.DaysOpen</td>
                <td>$@item.ChargebackAmount</td>
                <td>$@item.ChargebackBalance</td>
                <td>@item.FaultName</td>
                <td>@item.ResponsibleName</td>
            </tr>
        }
    </tbody>
</table>
}
@Scripts.Render("~/Scripts/bbc/Refresh.js")

Edited by Kevin:  Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.

Answers

  • kthorngrenkthorngren Posts: 20,144Questions: 26Answers: 4,736

    Cannot set property 'data' of null

    What does the JSON response look like? Use the browser's developer tools to look at the JSON response.

    In line 34 you have { "data": " DaysOpen", "name": "Days Open" },. There is a space before DaysOpen. That might not be a problem though.

    Your Datatavles structure looks to match the table structure. Could be the response JSON doesn't match.

    It looks like your View is building the initial table. Does the View populate the table with data?. Then your reloadTable() function is initializing Datatables with server side processing then using ajax.reload(). There are a few things that might be wrong with this depending on what you are needing to do:

    1. Do you need server side processing - see this FAQ. It requires this protocol to be followed.
    2. Generally you don't want to execute the Datatables initialization more than once, unless you are changing the initialization options. The code should probably be outside the reloadTable() function. Maybe more like this:

    function ReloadTable() { //console.trace("Our first Trace"); table.ajax.reload(); } $(document).ready(function () { var table = $('#DashboardTable').DataTable({ "processing": true, // for show progress bar "serverSide": true, // for process server side "filter": true, // this is for disable filter (search box) "orderMulti": false, // for disable multiple column at once "ajax": { "url": "/Chargeback/Index", "type": "GET", "datatype": "json" }, "columns": [ { "data": "ChargebackCode", "name":"Code" }, { "data": "StatusName", "name":"Status" }, { "data": "BusinessUnitName", "name":"Business" }, { "data": "InvoiceCode", "name":"Invoice" }, { "data": "OrderCode", "name":"Order"}, { "data": "PickTicketCode", "name":"Pick Tickets" }, { "data": "CustomerPo", "name":"Customer PO" }, { "data": "AssignedDepartment","name": "Assigned"}, { "data": "DivisionName", "name":"Division"}, { "data": "Customer", "name":"Customer" }, { "data": "WarehouseName","name": "Warehouse" }, { "data": "Coordinator","name": "Coordinator" }, { "data": "ChargebackDate","name": "Open Date" }, { "data": "ModDate", "name":"Last Activity" }, { "data": "ChargebackDeadline", "name": "Deadline" }, { "data": "ChargebackCloseDate", "name": "Closed Date" }, { "data": " DaysOpen", "name": "Days Open" }, { "data": "ChargebackAmount", "name": "Amount" }, { "data": "ChargebackBalance", "name": "Balance" }, { "data": "FaultName", "name": "Fault" }, { "data": "ResponsibleName", "name": "Responsible" } ] }); });

    If you continue to have problems please provide more details of what you are trying to do.

    Kevin

  • Katrell01Katrell01 Posts: 8Questions: 2Answers: 0

    Hello thank you for the response , so my goal is when the page initially loads it displays my DataTable when I press my checkbox opposed to loading the whole page it loads just the DataTable.

    1.Do you need server side processing ?
    If you are referring to the body of my table returning my data ;No, I just initially took this approach when pulling my data but I can remove it.

    Also it my Controller when returning data do I have to return it as Json as well?

  • kthorngrenkthorngren Posts: 20,144Questions: 26Answers: 4,736

    This page explains the expected data from the ajax request:
    https://datatables.net/manual/ajax

    Basically yes, it is expected to be JSON or you need to convert it as described in the doc.

    Datatables Server Side Processing is a protocol used to fetch only a page of data at a time. The server script needs to implement code to support this protocol. It is used for large datasets. You don't need to enable serverSide processing to simply use ajax. Unless you specifically need server side processing I would remove that config option.

    My recommendation is to return JSON data if you can and let Datatables initially populate the table using the example I posted above.

    Kevin

  • Katrell01Katrell01 Posts: 8Questions: 2Answers: 0
    edited July 2019

    Hello as we talked about before here is my controller:

    public ActionResult Index( )
    {
    var IncludeClosed = Request.Form["IncludeClosed"];
    if (IncludeClosed == "true,false")
    {
    var Chargeback = db.GetChargeback(true).ToList();
    ViewBag.IncludeClosed = true;
    return Json(Chargeback,JsonRequestBehavior.AllowGet);
    }
    else
    {
    var Chargeback = db.GetChargeback(null).ToList();
    ViewBag.IncludeClosed = false;
    return Json(Chargeback,JsonRequestBehavior.AllowGet);
    }
    }
    but I'm not sure if I should be returning the data this was b/c now instead of returning the datatable it returns just the data in JSON format , I'm I doing something wrong?

  • kthorngrenkthorngren Posts: 20,144Questions: 26Answers: 4,736

    Sorry, I'm not familiar with your controller code nor what it is returning. What do you see as the JSON response in the browser's developer tools?

    Are you getting any alert messages or browser console errors?

    What is happening with the page?

    What is the current page config?

    Kevin

  • Katrell01Katrell01 Posts: 8Questions: 2Answers: 0

    So initially I was returning my data as normal : return View(object) which displayed my DataTable correctly , but was getting an issue from my .js file b/c the data wasn't being returned correctly

    So I changed the data being returned from my ActiomMethod to return json:** return Content(JsonConvert.SerializeObject(object), "application/json");**
    but now my DataTable doesn't work properly it just displays the returned data as json

  • kthorngrenkthorngren Posts: 20,144Questions: 26Answers: 4,736

    DataTable doesn't work properly it just displays the returned data as json

    Not sure what this means. Can you post a link to your page so we can take a look?

    Kevin

  • Katrell01Katrell01 Posts: 8Questions: 2Answers: 0
    edited July 2019

    What I mean is it just returns raw json opposed the DataTable.

  • kthorngrenkthorngren Posts: 20,144Questions: 26Answers: 4,736

    What I mean is it just returns raw json opposed the DataTable.

    Where are you seeing the raw JSON? Web page, developer tools?

    What about the other questions I asked.

    Kevin

  • Katrell01Katrell01 Posts: 8Questions: 2Answers: 0

    1). Are you getting any alert messages or browser console errors?
    When I am returning Json I don't get any errors, but when I return as usual : return View (obj) ,
    I get error:

    1a).404 Not Found in console

    Alert message received:**
    1b). DataTables warning: table id=DashboardTable - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3
    1c). DataTables warning: table id=DashboardTable - Ajax error. For more information about this error, please see http://datatables.net/tn/7
    **
    2).What is happening with the page?
    ** It returns just raw Json on web page** opposed to the datatable
    What is the current page config?
    Not sure what you mean by this.

  • kthorngrenkthorngren Posts: 20,144Questions: 26Answers: 4,736

    What is the current page config? Not sure what you mean by this.

    Sorry, should have asked - What is your current Javascript (Datatables, etc) and HTML code?

    404 Not Found

    That is a server error, You will need to look at your server logs to see what is not found.

    Cannot reinitialise DataTable

    Sounds like you still have the Datatables initialization code in the ReloadTable function. Follow the steps in the URL: http://datatables.net/tn/3

    Ajax error

    The place to start is to follow the steps in the URL: http://datatables.net/tn/7

    You have a lot going on and it is difficult to help without actually seeing the page or data that is being returned. Can you post a link to your page so we can help debug?

    If not then, assuming you want to provide JSON data to Datatables, lets start by posting a snippet of the JSON response from the browser's developer tools.

    Kevin

This discussion has been closed.