How to reload the DataTable on Button click?

How to reload the DataTable on Button click?

rprahaladrprahalad Posts: 20Questions: 5Answers: 0
edited January 2021 in Free community support

I am trying to implement a very simple flow of the DataTable and I have read every article to get past it but I am still struggling with it. My flow is simple. I have only a drop down and a submit button on page load and user picks a value from it and I make a server side call and paint the datatable with the rows and plus with the Edit/Delete buttons, which when clicked, shows a bootstrap modal. If they CRUD a row, I refresh the grid when the modal is closed.

So far everything works but now if I go back and pick another value from the dropdown and hit Submit again, it keeps giving me "DataTable is not a function".

Here is my full code. Please note that whole cycle of 'Pick value from drop down->Submit->Load Results->Popup->Close Popup->Refresh grid on the main page' all works. But at that point, if I click on Submit again, it gives me the error.

Something happens after doing an ajax.reload() at the close the popup I guess. If I have a reference of the table in a variable like I do here, how can I make an ajax call through it? Like 'dataTable.ajax.reload()'? That way I can check isDataTable(), then just do dataTable.ajax.reload(). I tried that. No errors but the grid didn't change

<div id='divDetails'>
    <table id="dtProjects" class="table table-bordered table-striped">
            <thead>
                <tr style="background-color:#337ab7;color:white">
                    <th>ID</th>
                    <th>Project Name</th>
                    <th>Description</th>
                    <th>Project Managers</th>                  
                    <th>% Auto Check</th>
                    <th></th>
                    <th></th>
                    <th></th>
                </tr>
            </thead>
        </table>
</div>

var dataTable;

        $(document).ready(function () {

            $("#divDetails").hide();

            $(function () {

                $('#btnGetProjects').click(function (e) {

                        var projectId = $("#ddlProjects").val();
                        if ($("#frmProjects").valid()) {
                        }
                    else {
                            return false;
                        }

                        e.preventDefault();

                    $("#divDetails").show();

                        dataTable = $('#dtProjects').DataTable({
                            "ajax": {
                                "url": '@Url.Action("GetProjectsByProjectId")',
                            "type": "POST",
                            "datatype": "json",
                            "data": { "projectId": projectId},
                        },
                        "columns": [
                            { "data": "ID", "width": "150px" },
                            { "data": "Name", "width": "150px" },
                            { "data": "Description", "width": "150px", "orderable": false },
                            { "data": "ProjectManagersFormatted", "width": "150px", "orderable": false },

                            { "data": "AutoCheckPercentage", "width": "150px", "orderable": false },
                            {
                                "data": "ID", "width": "auto", "orderable": false, "render": function (data) {
                                    return '<a href="#" class="popup editButton" data-Project-id=' + data + ' data-project-id=' + $("#ddlProjects").val() + '">Edit</a>';                     }
                            },
                            {
                                "data": "ID", "width": "auto", "orderable": false, "render": function (data) {
                                    return '<a href="#" class="popup deleteButton" data-Project-id=' + data + '>Delete</a>';
                                }
                            },
                            {
                                "data": "ID", "width": "auto", "orderable": false, "render": function (data) {
                                    return '<a href="#" class="popup archiveButton" data-Project-id=' + data + '>Archive</a>';
                                }
                            }
                        ],

                        "bDestroy": true,

                        "language": {
                            "emptyTable": "No Projects found!"
                        }
                    })
                });

                $("divDetails").css("display", "block")
            });
        });


<!-- Modal Window Close-->
 $.ajax({
                type: "POST",
                url: url,
                data: $('#popupForm').serialize(),
                success: function (data) {

                    if (data.status) {
                        $('#ProjectModal').modal('hide');
                        dataTable.ajax.reload();

                    }
                    else {
                        $('#divError').addClass('alert alert-danger');
                        $('#divError').html(data.ErrorMessage);
                        $('#divError').focus();
                    }
                },
                error: function (request, status, error) {
                    alert(error);
                    $('#divError').html = error;
                }
            })

Answers

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    It's probably the scope of the variable. It's worth considering Editor as that'll make this process far easier.

    Colin

  • rprahaladrprahalad Posts: 20Questions: 5Answers: 0

    Thanks Colin. We just bought a license for the Editor. Let me try it out then because I am really stumped on this one. .

  • rprahaladrprahalad Posts: 20Questions: 5Answers: 0
    edited January 2021

    I just realized we have to make lot of code changes with Editor on these particular pages, as we have already written lot of backend code and databases and all that.

    I guess it's too late to start over again. For any new pages, Editor would probably be the way to go. So, I just have to get past this one error.

    The variable 'dataTable' is declared immediately after <script> and so, it is available globally. I am not sure why its throwing an error.

  • kthorngrenkthorngren Posts: 21,336Questions: 26Answers: 4,951

    If I understand correctly the process works the first time then fails the second with the DataTable is not a function error the second time. Is this correct?

    That would suggest something is changing the value of the dataTable variable. I would start by setting a break point at dataTable.ajax.reload(); to see what the value of dataTable is for the working and non-working condition.

    Without seeing the problem occur it will be difficult for us to give suggestions. Please post a link to your page or a test case showing the issue so we can help debug.
    https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case

    Kevin

  • rprahaladrprahalad Posts: 20Questions: 5Answers: 0

    Thanks Kevin. Yes, I soon will. I just extracted the relevant bit of the code and pasted it above but there is lot more going on and I am screwing something up. I will start debugging it now. But appreciate your response!

  • rprahaladrprahalad Posts: 20Questions: 5Answers: 0
    edited January 2021

    DataTable scripts are not getting loaded when I came back to the main grid page from the popup.

    This is how I have coded. I have an index.cshtml page which has a div tag and of course, this Index.cshtml has all the relevant Datatable libraries included, as that is the main landing page.

    Next, when I click on Add or Edit buttons, I am loading contents of 'Save.cshtml' in the above div and I am also handling submit button ajax call of 'Save.cshtml' as well, from the main Index page.

    So, not sure why the datatable scripts are getting lost when I come back from the popup. I can include the datatable files in the popup as well. But the search bar and pager bar gets loaded twice now.

  • rprahaladrprahalad Posts: 20Questions: 5Answers: 0

    One final question because I don't know how to proceed. How can I load the DataTable scripts on the fly? I have this code and I know this is perhaps a wrong way.
    Lile I said, If I include it in the popup page and submit that form successfully, it works. But If I just open the popup and immediately close it, I have this problem.

    Its perhaps an issue with the Bootstrap 3.0 popups BUT any idea how I can get past this?

    if (!$.fn.DataTable) {
                    alert("DataTable scripts not loaded");
                   // How do I load the scripts here? 
                }
    
  • rprahaladrprahalad Posts: 20Questions: 5Answers: 0

    I started off clean and in case someone has a similar issue, I added the Datatable files in _Layout.cshtml instead of adding it on index.cshtml page and removed reference to _layout.cshtml on the popup cshtml itself and it is working perfectly now.

This discussion has been closed.