0

I am using this dataTable code to load a table data.

var table = $('#fileInfoTable').DataTable({
    "sAjaxSource": "api/file/loadAll",
    "sAjaxDataProp": "",
    "order": [
        [0, "asc"]
    ],
    "aoColumns": [{
        "mData": "fileId"
    }, {
        "mData": "fileName"
    }, {
        "mData": "sentDate"
    }, {
        "mData": "direction"
    }, {
        "mData": "interfaceType"
    }, {
        "mData": "buisnessLine"
    }, {
        "mData": "vaultName"
    }, {
        "mData": "manageCompony"
    }, {
        "mData": "lastActivity"
    }, {
        "mData": "lastActivityStatus"
    }, {
        "mData": "feedbackName"
    }, {
        "mData": "feedbackDate"
    }, {
        "mData": "processDate"
    }, {
        "mData": "eventsAmount"
    }, {
        "mData": "goodEventsAmount"
    }, {
        "mData": "sourceId"
    }]
});

It works fine if I load it on page load but I need to be able to load the data by clicking a button and not on page load. How can I do it?

Edit: now I am using this code below and I can see the alert but the table is undefined

$(document).ready(function () {
    var table = $('#fileInfoTable').DataTable({
        data: [],
        "order": [
            [0, "asc"]
        ],
        "aoColumns": [{
            "mData": "fileId"
        }, {
            "mData": "fileName"
        }, {
            "mData": "sentDate"
        }, {
            "mData": "direction"
        }, {
            "mData": "interfaceType"
        }, {
            "mData": "buisnessLine"
        }, {
            "mData": "vaultName"
        }, {
            "mData": "manageCompony"
        }, {
            "mData": "lastActivity"
        }, {
            "mData": "lastActivityStatus"
        }, {
            "mData": "feedbackName"
        }, {
            "mData": "feedbackDate"
        }, {
            "mData": "processDate"
        }, {
            "mData": "eventsAmount"
        }, {
            "mData": "goodEventsAmount"
        }, {
            "mData": "sourceId"
        }]
    })

    $("#loadData").on('click', function () {
        alert("ppp:" + table.name);
        table.ajax.url("api/file/loadAll").load();
    })
});
9
  • Look at the api.ajax.reload() method. Not entirely clear what button is for and if it is for reload, changing url params or building table first time Commented Nov 12, 2017 at 16:03
  • Try take your code out of this $(document).ready(function() { s*** :) I cannot know for sure, but I have the feeling you are making it all too complicated and by that messes up the scope for your variables. Commented Nov 12, 2017 at 19:28
  • with out $(document).ready I am not getting the alert at all Commented Nov 12, 2017 at 20:54
  • @user7916020, where is the #loadData element located..? If it is inside the table, attach the event handler in a initComplete or drawCallback callback. Again, really hard just to guess without more info. Commented Nov 12, 2017 at 22:16
  • @davidkonrad ok I will add the html tomorrow. I think the problem is that the loadData button is not inside a specific div Commented Nov 12, 2017 at 22:58

3 Answers 3

1

Look at the code below.

Add Row API

Adding new data to a table is central to the concept of being able to dynamically control the content of a DataTable, and this method provides the ability to do exactly that. It will add a single row at a time - for the addition of multiple rows, either call this method multiple times or use this method's plural counterpart

var table = $('#example').DataTable();

table.row.add({
    "name": "Tiger Nixon",
    "position": "System Architect",
    "salary": "$3,120",
    "start_date": "2011/04/25",
    "office": "Edinburgh",
    "extn": "5421"
}).draw();

Clear API

When you perform an action such as adding or deleting a row, changing the sorting, filtering or paging characteristics of the table you'll want DataTables to update the display to reflect these changes. This function is provided for that purpose.

var table = $('#example').DataTable();

table
    .clear()
    .draw();

see documentation DRAW

$(document).ready(function() {
  var table = $('#example').DataTable();

  $("#add").on('click', function() {
    table.row.add([
      "Tiger Nixon",
      "System Architect",
      "Edinburgh",
      "54",
      "2011/04/25",
      "$3,120",
    ]).draw();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet" />

<input type="button" name="add" id="add" value="addrow" />

<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>

  <tbody>
    <tr>
      <td>Tiger Nixon</td>
      <td>System Architect</td>
      <td>Edinburgh</td>
      <td>61</td>
      <td>2011/04/25</td>
      <td>$320,800</td>
    </tr>

  </tbody>
</table>

Sign up to request clarification or add additional context in comments.

Comments

0

i have a example here

HTML

 ....
      <body>
            <table id="table_id" class="display"></table>

            <button id="customerSearchButton">CLICK AQUI - WACHIN (RECARGAR)</button>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
            <script src="http://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
    </body>
    ...

JS

<script>
      $(document).ready(function() {

        let table = $("#table_id").DataTable({
          columns: [{ data: "id" }, { data: "name" }, { data: "email" }],
          rowCallback: function(row, data) {},
          filter: true,
          info: false,
          ordering: false,
          processing: true,
          retrieve: true
        });
        $("#customerSearchButton").on("click", function(event) {
          $.ajax({
            url: "https://jsonplaceholder.typicode.com/comments?postId=1",
            type: "get"
          })
            .done(function(result) {
              console.log(result);
              table.clear().draw();
              table.rows.add(result).draw();
            })
            .fail(function(jqXHR, textStatus, errorThrown) {
              // needs to implement if it fails
            });
        });
      });
    </script>

Comments

0

Below code solved my purpose which is to load data on button click not on page load. I have created button with ID "eventlistview" and on click of this re initializing the data table.

// global variable
var grid;
jQuery(document).ready(function ($) {
 //initialise blank datatable on page load
  grid = $('#grd').DataTable({
           "processing": false, // control the processing indicator.
           paging: false,
            searching: false,
            info: false,
          // you can load data here also as per requirement
         });
});

jQuery(document).ready(function ($) {
  jQuery('#eventlistview').click(function () {
     // destroy datatable
     $("#grd").dataTable().fnDestroy()
     //reinitialise datatable
      $("#grd").dataTable({
          "processing": false, // control the processing indicator.
          "serverSide": true, // recommended to use serverSide when data is more than 10000 rows for performance reasons
          "ajax": {"url": "",
                    "type": "GET",
                   },
          "language": {"emptyTable": "No data found."
                      },
           columns: [{ "data": "TitleTxt" },
                      {"data": "StartDate"},
                      {"data": "EndDate"},
                    ],
           "order": [[0, "asc"]]            
                    });          
    });
});

https://stackoverflow.com/a/58976439/5685144

Hope it helps you too.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.