Tu Trinh
Tu Trinh

Reputation: 157

Cannot reinitialise DataTable when I reload datatables after perform edit page return to list page

On the list page user can edit info by click on Edit button and open details page for edit data. After edit done return list page. This my source code

My JS listUser.js is embbed in jsp file at the bottom listusers.jsp

<div class="c-body">
  <main class="c-main">
    <div class="container-fluid">
      <div class="fade-in" id="content">
        <div class="card">
    <div class="card-header">
      <div class="row">
        <div class="col-sm-4">List Users</div>
        <div class="col-sm-8 text-right">
            <button id="create_user" type="button" class="btn btn-primary">Tạo mới</button>
        </div>
      </div>
    </div>
    <div class="card-body">
      <table id="userTable" class="table table-striped table-bordered datatable">
        <thead>
          <tr>
    <th>Username</th>
    <th>Full Name</th>
    <th>Site</th>
    <th>Roles</th>
    <th>Areas</th>
    <th>Team</th>
    <th>Status</th>
    <th>Actions</th>
          </tr>
        </thead>
        <tbody>

        </tbody>
      </table>
    </div>
        </div>
        <script src="${contextPath}/user/listUser.js"></script>
      </div>
    </div>
  </main>
</div>

listUser.js

$( document ).ready(function() {
    var userTable = $('#userTable').DataTable( {
        "processing": true,
        "serverSide": true,
        "pageLength": 10,
        "ajax": {
            "url": "/user/paginated",
            "data": function ( data ) {
         }},
        "columns": [
                    { "data": "username", "name" : "Username", "title" : "Username", "defaultContent" : ""},
                    { "data": "full_name", "name" : "Full Name" , "title" : "Full Name", "defaultContent" : ""},
                    { "data": "site_code", "name" : "Site" , "title" : "Site", "defaultContent" : ""},
                    { "data": "user_roles", "name" : "Roles", "title" : "Roles", "defaultContent" : ""},
                    { "data": "user_areas", "name" : "Areas", "title" : "Areas", "defaultContent" : ""},
                    { "data": "team_code", "name" : "Team", "title" : "Team", "defaultContent" : ""},
                    { "data": "status", "name" : "Status", "title" : "Status", "defaultContent" : ""},
                    { "targets": "no-sort", "orderable": false, "data": "null", "name" : "Thao tác", "title" : "Thao tác", "defaultContent" : "<button id='updateUser' name='updateUser' class='btn btn-primary btn-edit' type='button' aria-pressed='true'>Sửa</button>"}
                ]
    });

    $('#userTable').on('click', '.btn-edit', function(){
       var data = userTable.row( $(this).parents('tr') ).data();
       //alert(data.user_id);
       let url = "user/updateUser?id=" + data.user_id;
       $("#content").load(url);
    });

    $(document).on('click', '#update_user', function(){
            updateUser();
    });

    function updateUser() {
        ...

        var data = {
            ...
        };

        var json = JSON.stringify(data);

        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
              myObj = JSON.parse(this.responseText);
              if(myObj.status == "1"){
                  $("#content").load("user/list");
              }
            }
         };
        xhr.open("POST", "/user/update");
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        xhr.send(json);
    }
});

The problem I occurred DataTables warning: table id=userTable - Cannot reinitialise DataTable.

Thanks you.

Upvotes: 0

Views: 575

Answers (1)

emi
emi

Reputation: 3070

From DataTable Docs (first result in search engine with the warning message you provided):

DataTables has a wide range of configuration options which can be used to customise the table at initialisation time, but only at initialisation time. After a DataTable has been initialised any attempt to use these options will result in an error.

Simply put, DataTables does not allow initialisation options to be altered at any time other than at initialisation time. Any manipulation of the table after initialisation must be done through the API [...]

You are not showing how you initialize DataTable, so I can't help you further, unless you update your answer with more information.

Edit

After gathering more info from you, I now can understand what you are trying to do.

Essentially: DataTables expects it's DOM elements to be managed by itself. Once you initialize a DataTable, you should not manipulate any DOM related to it. If you want to show something like the user editing page and go back to the table after save, you need to choose one of the next 2 options:

  • Completely unmount the DataTable before showing the user edit page and re-initialize it after saving user data and gathering new DataTable data from server.
  • Don't detach DataTable DOM: show user form in a modal, or hide the DataTable instead of removing it, and unhide it again after user data has been saved. Updated data will need to be reinjected into a living DataTables, which I think will need the use of the .ajax.data initialization option.

Depends on how much data is being transferred and processed I'd choose one or the other.

Upvotes: 1

Related Questions