38

I obtain table data from database via AJAX request. And I need to change data parameter in AJAX request and refresh the table.

I am refreshing table with command

$('#table1').DataTable().ajax.reload();

I have the following code

$('#table1').DataTable({

    /* SERVER SIDE PROCESSING */
                "serverSide": true,
                "ajax":
                    {
                        "url": "Home/Search",
                        "type": "POST",
    
                        "data": {
                            'searchType': GetSearchType(),
                            'searchText': GetSearchText()
                            //'searchType': $.mynamespace.searchType
                            //'searchText': $.mynamespace.searchText
                            //'searchType': localStorage.getItem("searchType"),
                            //'searchText': localStorage.getItem("searchText"),
                        }
                    }
            });

But after AJAX reload, original request to the server is sent and new parameter values are ignored. I tried pass the data to the request via function, global variable and browser storage but none of the approach work. On the internet I find solution with

aoData.push() 

function but I don't know how to use it.

My version of jQuery DataTables is 1.10.7.

I also tried destroying and recreating the table with this code:

$('#table1').DataTable({
        "ajax":
            {
                "url": "Home/Search",
                "type": "POST",

                "data": {
                    'searchType': GetSearchType(),
                    'searchText': GetSearchText()
                }
            },
        "destroy" : true
    }).ajax.reload();

but I am getting error message:

DataTables warning: table id=table1 - Ajax error (http://www.datatables.net/manual/tech-notes/7)

The parameters dictionary contains a null entry for parameter 'draw' of non-nullable type 'System.Int32'

5 Answers 5

65

You can use function as a value for ajax.data option as shown below.

That way your code will be run every time the client makes request to the server and not once as with your initial code.

$('#table1').DataTable({
   "serverSide": true,
   "ajax": {
      "url": "Home/Search",
      "type": "POST",
      "data": function(d){
         d.searchType = GetSearchType();
         d.searchText = GetSearchText();
      }
   }
});

Then use $('#table1').DataTable().ajax.reload() when you need to reload the table or $('#table1').DataTable().ajax.reload(null, false) if you don't want to reset the current page. See ajax.reload() for more information.

3
  • 3
    Thanks. Note that the method above works for updating parameters for table.ajax.reload() calls as well, not just table initialization. This is true even if you use jquery (or javascript) to update parameters from form element current content and/or model values via razor. Tested in DataTables v1.10+ with good results. :)
    – IdahoB
    Aug 16, 2018 at 17:45
  • It's not working for me, I get: Uncaught TypeError: Cannot read property 'reload' of undefined Feb 14, 2019 at 20:31
  • 2
    @MichaelFever, make sure you're using DataTable() and not dataTable(). Feb 15, 2019 at 17:16
13
$('#table1').DataTable().ajax.url("?some_param=1&another=2").load();

This is an another solution. Add your params inside default datatable params.

How to set dynamically the Ajax URL of a dataTable?

1
  • 3
    This is exactly what I needed! Was able to avoid having to do serverSide processing logic (serverSide: true} by using this solution when creating my own pagination logic to control number records being displayed at one time, thank you!
    – ttemple
    Sep 25, 2020 at 20:51
5

Okay I found the solution, in the reinitializing of the table, it is needed to specify all settings again otherwise they are taken from default. so the final code is

$('#table1').DataTable({
            "iDisplayStart": 0,
            "iDisplayLength": 50,
            "bPaginate": true,
            "bSort": false,
            "serverSide": true,
             /* and all others settings others than default */
        "ajax":
            {
                "url": "Home/Search",
                "type": "POST",

                "data": {
                    'searchType': GetSearchType(),
                    'searchText': GetSearchText()
                }
            },
        "destroy" : true  /* <---- this setting reinitialize the table */
    }).

but if someone will find better solution, please share it.

1
  • 2
    Perhaps the 'destroy' parameter worked in earlier versions, but at least in versions 1.10 or newer of DataTables, it no longer works (hence the down vote - sorry!). Using a function as described in the first answer does work, however.
    – IdahoB
    Aug 16, 2018 at 17:43
3

This is how i accomplish it:

var onSearchClick = function () { search(); };

    var search = function () {


        var startDate =  $('#datetimepicker1').find("input").val();
        var endDate = $('#datetimepicker2').find("input").val();

        $.ajax({
            type: "GET",
            url: "/api/getByDate?startDate=" + startDate + "&endDate="+endDate,
            datatype: "json",
            traditional: true
        })
        .done(function (data) {

          var table = $('#data-table-1').DataTable({
              data: data.data,
              destroy: true,
              "columns": [
             { "data": "id" },
             { "data": "id2" },
             { "data": "id3" }
              ],
              "columnDefs": [
           {
               "targets": [1],
               "visible": false,
               "searchable": false
           },
            {
                "targets": [2],
                "visible": false,
                "searchable": false
            }],
              "sPaginationType": "full_numbers"
          });
      });
    };
1

AJAX loads header as a variable on first time when page loads. When you changed the headers and do some sorting/searching. New headers will not be set unless you set new headers using "beforeSend".I have provided the sample code.

Try this,

$scope.dtOptions = DTOptionsBuilder.newOptions()
.withOption('ajax', {
    url: 'url',
    'beforeSend': function (request) {
        request.setRequestHeader("Authorization","eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9");
        request.setRequestHeader("Subscription-Key","1d64412357444dc4abc5fe0c95ead172");
    } ,

    //},
    type: "POST",
    cache: false, // It will not use cache url

})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.