Disable initial automatic ajax call - DataTable server side paging
Asked Answered
N

4

46

I have a dataTable initialized with server side paging and it is working fine. This table triggers ajax, pulls data and renders onto the table during initialization. However I need empty table initially and load table data on click of a button using load() or reload() like:

myTable.api().ajax.reload();

Here is my table initialization:

function initTestTable(){
    myTable =  $('#testTable').dataTable({
    "processing": true,
    "serverSide": true,
    "ajax": {
        "url": "testTableData.html",
        "type": "GET",
    },
    "columns": [
        { "data": "code" },
        { "data": "description" }
    ]
 });
}

There should be a way to restrict the loading of table during initialization? I read the documentation but could not find. Please suggest.

Needlepoint answered 2/7, 2015 at 3:56 Comment(4)
So...were you able to get it working?Lilialiliaceous
@Lilialiliaceous - Yes, by using the workaound of passing request parameter to identify the event origin, I am able to get it work. Please refer answer details posted by me below. I still wonder as to why deferLoading did not work for me. Thank you :)Needlepoint
i found the solution, very simple, follow in this link: https://mcmap.net/q/373366/-datatables-do-not-send-ajax-request-at-the-initializationUnhook
Use this solution for reload data with ajax with same url: https://mcmap.net/q/373366/-datatables-do-not-send-ajax-request-at-the-initializationFlynn
L
88

You could use the deferLoading parameter and set it to 0. This will delay the loading of data until a filter, sorting action or draw/reload Ajax happens programmatically.

function initTestTable(){
    myTable =  $('#testTable').dataTable({
    "processing": true,
    "serverSide": true,
    "deferLoading": 0, // here
    "ajax": {
        "url": "testTableData.html",
        "type": "GET",
    },
    "columns": [
        { "data": "code" },
        { "data": "description" }
    ]
 });
}

To trigger the Ajax when the button is clicked you can have something like the following in the handler:

function buttonClickHandler(event){
  $('#testTable').DataTable().draw();
}

See example below for demonstration.

$(document).ready(function() {
  // AJAX emulation for demonstration only
  $.mockjax({
      url: '/test/0',
      responseTime: 200,
      response: function(settings){
         this.responseText = {
            draw: settings.data.draw,
            data: [
              [ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "$320,800" ],
              [ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "$320,800" ],
              [ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "$320,800" ],
              [ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "$320,800" ],
              [ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "$320,800" ],
              [ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "$320,800" ],
              [ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "$320,800" ],
              [ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "$320,800" ],
              [ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "$320,800" ],
              [ "Tiger Nixon", "System Architect", "Edinburgh", 61, "2011/04/25", "$320,800" ]
            ],
            recordsTotal: 1000,
            recordsFiltered: 1000
         };
      }
  });

  $('#example').DataTable({    
    "processing": true,
    "serverSide": true,
    "deferLoading": 0,
    "ajax": {
        "url": "/test/0",
        "type": "GET"
    }    
  });
      
  $('#btn-reload').on('click', function(){
     $('#example').DataTable().draw()  
  });
});
<!DOCTYPE html>
<html>

<head>
<meta charset="ISO-8859-1">
<link href="//cdn.datatables.net/1.10.5/css/jquery.dataTables.min.css" rel="stylesheet"/> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 
<script src="//cdn.datatables.net/1.10.5/js/jquery.dataTables.min.js"></script>
<script src="http://vitalets.github.com/x-editable/assets/mockjax/jquery.mockjax.js"></script>
  
</head>
<body>
<p>
<button id="btn-reload">Reload</button>
</p>
<table id="example" class="display" cellspacing="0" width="100%">

<thead>
   <tr>
      <th>Name</th>
      <th>Position</th>
      <th>Office</th>
      <th>Age</th>
      <th>Start date</th>
      <th>Salary</th>
   </tr>
</thead>

<tfoot>
   <tr>
      <th>Name</th>
      <th>Position</th>
      <th>Office</th>
      <th>Age</th>
      <th>Start date</th>
      <th>Salary</th>
   </tr>
</tfoot>

<tbody>
</tbody>
</table>
</body>
</html>
Lilialiliaceous answered 2/7, 2015 at 4:2 Comment(13)
"deferLoading": 0, is not making any difference. I am still getting my table loaded on init.Needlepoint
Am able to do reload using myTable.api().ajax.reload();, but I need my table empty on load - which is not happening with "deferLoading": 0Needlepoint
It's not working? Weird, this option specifically address your need, it should work...Try changing the deferLoading value from 0 to [0]Lilialiliaceous
I tried all the options but no luck. Yes it looks so weird. Even yesterday I tried this option.Needlepoint
I am using ajax type as post "type": "POST". I dont think that will have anything to do with my issue. Anyway I will change that to GET and see.Needlepoint
Mmmh, I'd try to change the datatable version. Either update it or get an older one, depending on which you have. Did you try random values for the deferLoading option? stuff like -1, 2, true, etcLilialiliaceous
As expected the ajax type has no effect. I am using version 1.10.5Needlepoint
Tried various values like true/false, 1, 2, 15.. Not working. Let me see whats going inside using firebug debugging.Needlepoint
Seems deferLoading is available in dataTables 1.10 but not 1.9 or lower. In 1.9 or lower it is iDeferLoading.Steviestevy
Although the solution did not work for my environment then & I got through with some workaround, I would accept this answer as there are many upvotes and seem to be working in other versions of DataTable than what I used then.Needlepoint
Note that it is required to also have serverSide set to true when using deferLoading.Expiatory
I tried but not working, see my answwer for the simple working recipeZohar
from its documentation on datatables.net/reference/option/deferLoadingDeprecated As of v1.13 this feature has been deprecated. This feature has not yet been scheduled for removal, but its use is discouraged and the alternatives discussed below should be used. This option is largely irrelevant for the modern web. It was added when search engines wouldn't index Ajax data, but that is no longer the case, and this option just means you need to duplicate rendering logic in the server and the client. It will be removed in v2.Analysis
N
1

I could do it with a workaround by passing an extra parameter with the URL to identify the event.

For example, for on load I initialized the data table with action="load" as query param and for other action like search, am passing action="search". With this I, at the back end, will be able to identify the call origin. If it is anything other than "load", I am pulling the data & passing (as the implementation is now). Otherwise (if "load") then I am passing empty data, which will show me "No Data Found" message as if it did not made the ajax call.

Here is my code - Table initialization:

function initTestTable(){
    myTable =  $('#testTable').dataTable({
    "processing": true,
    "serverSide": true,
    "ajax": {
        "url": "testTableData.html?action=load",
        "type": "GET",
    },
    "columns": [
        { "data": "code" },
        { "data": "description" }
    ]
 });
}

For events other than load (say button click):

    var newUrl = 'testTableData.html?action=search';
    myTable.api().ajax.url(newUrl).load();

This was the one I had to take up without modifications to table init that would cause errors.

Thank you @JSelser and @davidkonrad for all your suggestions :)

Needlepoint answered 2/7, 2015 at 8:48 Comment(1)
This is too complex, deferLoading should work just fine. See the example I added to @Lilialiliaceous answer, which uses DataTables 1.10.5.Osborn
A
0

This is how I initially load my empty dataTable on page load. Then I load it with data via ajax using an eventListener. I couldn't find any documentation I just kind of played around with it and it works like a charm.

ref files - dataTables.js, table-advanced.js

$(document).ready(function(){
   option = "I";
  // pick a table list or something
  $("#dropdownList").on("change", function(){
      option = $('option:selected:not(:disabled)',this).val();
    if($.fn.DataTable.isDataTable('#table_001')){
       $('#table_001').dataTable().fnDestroy();
       InitDataTable(option); 
     }
     else{
       InitDataTable("disabled");   
     }    
    });

     //add/delete/update a row maybe?
     $("#signupForm #add_btn").on("click",function(e){
       if($("#signupForm").valid()){
            var oTable1 = $('#table_001').DataTable(); ///load .ajax structure 
             //Successful Submit!
             oTable1.ajax.reload(); 
            $("#note").html(<img src="/images/loading.gif" alt="loading">');
        }
     });

     //On draw occurs everytime you call table.ajax.reload(); 
     $('#table_001').on( 'draw.dt', function () { 
            if(option !== "I")
                  var evtname = $('select[name="EVENT"] option:selected:not(:disabled)').text();

            if(evtname !== undefined)
                $("#event_name").html("The " + evtname + " Signup Sheet").addClass("xs-small");
            // keep track of values for table input fields on each draw
            $("[aria-controls='table_001'][type='search']").attr('hth_orig',$("            [aria-controls='table_001'][type='search']").val());
            //Don't initialize on draw 
            TableAdvanced.init('table_001','N');
});


  var InitDataTable = function(choice){

            var oTable1 = $('#table_001').dataTable( {
                "processing": true,
                "serverSide": true,
                "lengthMenu": [10,25,50,100], // records pulldown
                "iDisplayLength": 25, // # records to initially display
                "ajax": {
                    "url": "http://www.domain.com",
                    "data": function (d) { // pass additional        
                                d.user = user; 
                                d.choice = choice; 
                                d.cols = "15"; // TOTAL <td> tags per <tr> tag  
                    },
                    // Load attendee total and pending total sections 
                    complete: function (d) {
                        recordstotal = d.responseJSON.recordsTotal;
                        attendeetotal = d.responseJSON.attendeeTotal;
                        //console.log(JSON.stringify(d.responseJSON.data));
                        if ( attendeetotal == '0') {
             $("#totalAttendees").html("No one has signed up for this event yet");
                        }
                        else {
        $("#totalAttendees").html("Event Total: " +  attendeetotal + " attendees");                     
                        }  
                        $("#add-atn").removeClass("hidden");
                    } 
                }, 
                // insert code to execute after table has been redrawn
                "fnDrawCallback": function( oSettings ) {
                    // Column filtering
                    var table = $('#table_001').DataTable();
                    $("#table_001 tfoot th").each( function ( i ) { // i = 0,1...
                        if($.trim($(this).html()) != '') {
                            save_html = $(this).html();
                            $(this).empty(); 
                            var select = $(save_html)
                            .appendTo( this )
                            .on( 'change', function () {
               table.column( i, { filter: 'applied'                }).search($(this).val()).draw();
                            }); 
                            $("#table_001 tfoot th:eq("+i+") input").val(save_value);
                        } 
                    });     
                    //console.log($("#table_001 tfoot th").length);
                 },

                "columns": [// set "data" to next sequential number in double quotes
                        {"data":"0",// Set "name" to field name that will be refd
                        "name": "skip"},        
                        {"data":"1", 
                        "name": "skip"}, 
                        {"data": "2",
                        "name": "skip"},
                        {"data":"3", 
                        "name": "lname"},
                        {"data":"4", 
                        "name": "fname"}
                          {"data":"5",
                           "name": "skip"}
                ],      
                "columnDefs": [                    
                        // what columns should be hidden?       
                        {
                        "targets": [1], // what element starting with 0
                        "class":"hidden" // class to attach to <td>
                        },
                        // what columns should NOT be sortable?       
                        {
                        "targets": [0,1,2,5,6,7,8,9,12,13,14], 
                        "sortable": false, // sortable?
                        },
                        // what columns should NOT be searchable?       
                        {
                        "targets": [0,1,2,6,7,8,9,12,13,14],  
                        "searchable": false, // searchable?
                        }
                ],  
                "createdRow": function( row, data, dataIndex ) { 
                    //manipulate the specific column in the row   
                     //$(row).addClass( 'form-group' ); 
                     // $('td', row).eq(2).addClass('form-group'); // Added to <td>

                 },
                // Specify initial sort order       
               "order": [[ '10', "desc" ],[ '11', "desc" ],['3',"asc"],['4',"asc"]]   
            });

            // handle 1st page table load initialization using 
            TableAdvanced.init('table_001','Y');

    });
    }

NOTE: You could add some logic that selects a default option if there is one that is available and not disabled.

Ahead answered 19/11, 2016 at 5:52 Comment(0)
Z
0

The correct (working) way is:

$(document).ready(function() {
  tableConfig = {
      pageLength: 5,  
      "columns": [
            { "data": "name" },
            { "data": "position" },
            { "data": "office" },
            { "data": "extn" },
            { "data": "start_date" },
            { "data": "salary" }
        ]
    };
  
  var table = $('#example').DataTable(tableConfig);

  $('#ajaxLoad').on('click', function() {
    tableConfig.ajax = {
      "url": "ajax/objects_root_array.txt",
      "dataSrc": ""
    };    
    
    table.destroy();
    table = $('#example').DataTable( tableConfig );
  })
} );

Working example

Source

Zohar answered 24/8, 2022 at 16:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.