0

I have a JQuery Datatable that is defined in a JS Module. And, elsewhere, I'm trying to reload it with the help of Datatable's ID selector. Here, I want to pass in new request post data which I'm having trouble with.

My attempt :

In Module A:

$(selectors.Datatable)
    .DataTable({
        bProcessing: true,
        serverSide: true,
        ajax: {
            data: initialPostData,
            url: urls.read,
            method: 'POST'
        },
        columns: [...],
        autoWidth: false,
        searchDelay: 500
    });

In Module B:

var newPostData = [...];
var dataTableWidget = $(selectors.datatableSelector).DataTable();
dataTableWidget.ajax.params(newPostData);
dataTableWidget.ajax.reload();

I was expecting dataTableWidget.ajax.params(newPostData); should be post new data in the ajax request. But it isn't.

Update

params is not the one that is going to help here. From documentation:

Get the data submitted by DataTables to the server in the last Ajax request

halfer
  • 19,824
  • 17
  • 99
  • 186
BetterLateThanNever
  • 886
  • 1
  • 9
  • 31
  • 1
    If you want to re-execute a DataTables ajax request - but with different `data` (i.e. data which is submitted to the server as part of the request) - you have to provide a function to the `ajax.data` option. There is an example [here](https://stackoverflow.com/questions/66243388/how-to-reload-datatable-by-using-new-url-and-some-parameters-without-reinitializ/66244738#66244738). Note the **warning** in that answer, relating to server-side processing, which I see you are also using. (And I see you are already using `ajax.reload()` to trigger the reload.) – andrewJames May 03 '21 at 23:52
  • This example only works if both initial load and reload are within the same module. In my case, its not. They are in two different modules. – BetterLateThanNever May 04 '21 at 00:11
  • _They are in two different modules_ Yes, that is clearly stated in the question. Is there something preventing your 2 different modules from accessing a common function? – andrewJames May 04 '21 at 00:25
  • Also (more out of curiosity), why is there `selectors.Datatable` in A, but `selectors.datatableSelector` in B? Is that not also something which could also be common to both A and B? If I am off-course here, maybe a [mre] would help to clarify. – andrewJames May 04 '21 at 00:27
  • Both selectors.Datatable in A and selectors.datatableSelector in B holds save value. They have different names in different Modules. The function that gets the request data is tightly coupled in Module B and cannot be exported to a common Module. – BetterLateThanNever May 04 '21 at 00:32

1 Answers1

1

After looking into the documentation of JQuery Datatable, I found this as a workaround.

dataTableWidget.settings()[0].ajax.data = newPostData;

dataTableWidget.ajax.reload();
BetterLateThanNever
  • 886
  • 1
  • 9
  • 31