Data tables are updating the wrong row

Data tables are updating the wrong row

umschoolumschool Posts: 5Questions: 3Answers: 0
edited November 2021 in Free community support

Good afternoon, in the table I use the render of the "Sign document" button, after clicking an ajax request is executed in which the answer comes:

{
  "data": [
    {
      "id": 1236,
      "created_date": "03.11.2021 15:48:36",
      "is_revoked": true,
      "is_customer_signed": true,
      "is_contractor_signed": true,
      "type": 2,
      "created_by": "aaaa",
      "opened_by_user": true,
      "document_amount": "",
      "employee_vk_id": 111111111,
      "nickname": "vvvvvv",
      "login": "vvvv11",
      "contractor": "bbbbbbbbbb"
    }
  ],
  "response": true
}

Part of the code from the ajax request that I am updating the page with.

success: function (result) {
      if (result.response) {
        let dataRow = result.data[0];
        let allRows = tableDoc.rows().data();

        for (let i = 0; i <= allRows.length; i++) {
          if (allRows[i].id === dataRow.id) {
            tableDoc.row([i]).data(dataRow).draw();
          }
        }
        $("#subscribeDoc").modal("hide");
      }
    }

The problem is that the code does not update the line, but replaces the next one with new data. The mistake is that I'm accessing row incorrectly?

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,327Questions: 26Answers: 4,949
    Answer ✓

    The default order returned using rows() is the current order of the table. You are using tableDoc.row([i]) to select the row to change. This uses the row index which is original data order (unsorted order). The row you are comparing allRows[i] is not the same as the row you are updating with tableDoc.row([i]).

    One option is to use the selector-modifier of {order:'index'} to get the rows in line 4, for example: let allRows = tableDoc.rows( {order:'index'} ).data(); to loop through in the unsorted order.

    A more efficient solution would be to use rowId set to the id. In the success function you can get the id and update the row directly using the row-selector as an id selector shown here. This will eliminate looping all the rows. Something like this:

    success: function (result) {
          if (result.response) {
            let dataRow = result.data[0];
            let id = dataRow.id;
            tableDoc.row( "#" + id ).data(dataRow).draw();
    
            $("#subscribeDoc").modal("hide");
          }
        }
    

    Kevin

  • umschoolumschool Posts: 5Questions: 3Answers: 0

    I fixed everything according to your instructions and it worked!
    Thank you very much.

Sign In or Register to comment.