Datatable Ajax SearchParameters

Datatable Ajax SearchParameters

nwickinwicki Posts: 21Questions: 8Answers: 0

I have a custom made filter function on my website where I am using one of your datatables. When initializing the datatable one can add parameters with the "data" option. I want to do this, but only if search terms are provided. The amount of search terms and their key-value pairs will be known at runtime which is why I can't define them at datatable initialization.

I am basically looking for a possibility to simply add (remove) up to n parameters to (from) the request url:

exampleUrl?draw=1&columns...&key1=value1&...&keyN=valueN&_=1581171459716

I know about the option to add parameters at runtime by using a function for "data", but I didn't understand how to use it in my case. Maybe someone can provide an example of how to do this.

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 61,436Questions: 1Answers: 10,049 Site admin
    Answer ✓

    ajax.data is indeed how you could do this:

    ajax: {
      url: ...,
      data: function (d) {
        d.newParam = 'hello'; // add
        delete d.columns; // remove
      }
    }
    

    Allan

  • nwickinwicki Posts: 21Questions: 8Answers: 0

    Thanks. I made a trivial mistake and also understand now how it works. I am using a global variable to provide the parameters to the data function.
    But isn't there any other way to provide them? Depending on the call, I have a variable amount of parameters which is why I cannot provide them by hand and I'd like to avoid global variables as much as possible. Maybe the answer is trivial (since I am not that experienced in javascript or jQuery), but I could not find a way to do it.

  • nwickinwicki Posts: 21Questions: 8Answers: 0

    Sorry for the late reply. I solved it the following way. globalFilter is a javascript object which I manipulate externally to provide the filters I need. After the request is modified, I reset my filter such that the request is reset for every invocation. I hope it helps someone.

    ajax: {
       url: url.example,
       data: function(d){
          var request = $.extend({}, d, globalFilter);
          globalFilter = { };
          return request;
       }
    }

This discussion has been closed.