Using filters with Datatables?

Using filters with Datatables?

hellow0rldhellow0rld Posts: 2Questions: 1Answers: 0
edited October 2020 in Free community support

Link to test case: https://pastebin.com/qzmjLVBF
Debugger code (debug.datatables.net): I don't know, NA
Error messages shown: NA
Description of problem: I would like to know how to use select box filters with datatables. I've managed to hack it so that it does a refresh when I change the filter but it's not how I would like to do it. I would just call $("#table").DataTable({}) again but it doesn't allow that. I've had a look through the list of AJAX capabilities but I can't see what I need.

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,516Questions: 1Answers: 10,473 Site admin
    Answer ✓

    The issue at the moment is that "url":"fetch.php?filter="+filter, is only ever evaluated once. What you want is that every time you reload the data for the table (which you would do using ajax.reload() is for the filter value to re-evaluated. For that, use ajax.data:

    ajax: {
      url: 'fetch.php',
      data: function (d) {
        d.filter = $('#filter').val();
      },
      dataSrc: '',
      type: 'GET'
    }
    

    Also make sure you assign the DataTable to a variable:

    var table = $('#table').DataTable({
    

    And in your change event handler call ajax.reload():

    table.ajax.reload();
    

    Job done ;)

    Allan

  • hellow0rldhellow0rld Posts: 2Questions: 1Answers: 0

    Brilliant! It worked first time thanks. In this example:

    1. I looked in the documentation for ajax reload but I did not understand "data.json" in the first example. Where is this data coming from? Does it just represent the data which would be used in a full example?
    2. In ajax.reload, is ajax a classname without an instantiated object? Is there a way to get back a list of classnames & methods which are available? Maybe in the browser or VS Code. I'm just trying to figure out what is available to me.

    Javascript syntax never gets any easier :s

  • allanallan Posts: 63,516Questions: 1Answers: 10,473 Site admin

    I looked in the documentation for ajax reload but I did not understand "data.json" in the first example. Where is this data coming from?

    It just an example file name. You could have /my/really/long/path/to/myData or anything else - as long as it returns valid JSON.

    In ajax.reload, is ajax a classname without an instantiated object?

    Not it isn't a "class" in the technical term - it is just an object with properties attached to it. The full list is in the reference.

    Our latest package of DataTables has typescript typings in it, so if you are using TypeScript it should auto complete when everything is setup and working.

    Allan

This discussion has been closed.