Best practice for updating table with data from wrapped Ajax responses (WordPress)

Best practice for updating table with data from wrapped Ajax responses (WordPress)

tdemelletdemelle Posts: 3Questions: 1Answers: 0

I have a DataTable initialized with JavaScript data:

let table = new DataTable("#my-table", {
   data: initialData  // Direct array of row data
});

When I later need to update the table with fresh data, it comes from an Ajax response that wraps the data. For example, WordPress Ajax returns:

{
    success: true,
    data: {
        // The actual array of row data is nested here
        data: [ {row1}, {row2}, ... ]
    }
}

What's the best practice for:

  1. Handling wrapped Ajax responses in general when updating table data
  2. Specifically handling WordPress wp_send_json_success() responses

I want to avoid reinitializing the table if possible and use DataTables' built-in methods correctly.

Replies

  • allanallan Posts: 64,059Questions: 1Answers: 10,559 Site admin

    Use clear() followed by rows.add() and draw() - e.g.:

    table
      .clear()
      .rows.add(myNewData)
      .draw();
    

    The value you pass to rows.add() should be the data array you want to display in the DataTable, so it might be something like json.data.data in this case.

    Allan

  • tdemelletdemelle Posts: 3Questions: 1Answers: 0

    Thank you. That was the key I needed!

Sign In or Register to comment.