0

I would like to fetch data on page load and then have filters that can be clicked to refetch the data. The query is a post request because the query parameters are complex and should be represented as json for logical grouping.

The code is as follows:

// table initialization
table = $('my_table').DataTable({
  processing: true,
  ajax: {
    url: 'api/v1/get_documents',
    type: 'POST',
    contentType: "application/json; charset=utf-8",
    data: () => {
      return JSON.stringify({
        doc_filters: {
          archived: false,
          doc_type: 'accounting'
        },
      })
    },
  },
  columns: my_columns,
});


$('#archive_button').click(() => {
  table.ajax.data = () => {
    return JSON.stringify({
      project_filters: {
        archived: true,
      }
    });
  };
  table.ajax.reload();
})
I would like the request body to reflect the new project_filters state with archived = true, refetch the data with this new request body, and update the table to reflect the new data. This does not update the request json body.

2
  • Just a suggestion, as I have not tested your specific scenario. The reload() function re-uses the ajax definition as defined in the DataTable configuration. Although you are using a function for your data, the actual archived value in the function is hard-coded to false. My approach in similar situations is to make that a variable (initially set to false), and then have the click() event update the value of the variable to true, prior to calling reload(). There may be other/better approaches, also. Commented May 10, 2022 at 15:14
  • I was able to use your philosophy to come up with a solution. Thank you @andrewJames Commented May 10, 2022 at 15:36

1 Answer 1

1

With the help of @andrewJames's suggestion I was able to refactor my code as follows:

// table initialization
table = $('my_table').DataTable({
  processing: true,
  ajax: {
    url: 'api/v1/get_documents',
    type: 'POST',
    contentType: "application/json; charset=utf-8",
    data: () => {
      archiveStatus = $('#archive_button').val();
      documentType = $('#document_type').val();
      return JSON.stringify({
        doc_filters: {
          archived: archiveStatus,
          doc_type: documentType
        },
      })
    },
  },
  columns: my_columns,
});


$('#archive_button, #document_type').click(() => {
  table.ajax.reload();
})

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.