0

I have written one function that makes one ajax call and gets the data and creates a table.I calling this function again and again.But while doing that I am getting reinitialization of table error.Can someone please help me to fix the issue.

Function :

function getLibraryFilesStudent() {
  var reqBody = {
    "uploader": Cookies.get('user')
  };
  $.ajax({
    url: '../library/libraryfilegetlist',
    data: JSON.stringify(reqBody),
    dataType: 'json',
    headers: {
      "Content-Type": "application/json",
      "Accept": "application/json"
    },
    error: function(data) {
      console.log(data);
    },
    success: function(data) {
      if (data.length) {
        var trHTML = [];
        for (var i = 0; i < data.length; i++) {
          var test = '<input type="radio" class="radio" name="selectFile" value=' + data[i].id + "," + data[i].keyword + ",flag=1" + '>';
          trArr = [data[i].name, data[i].keyword, test]
          trHTML.push(trArr);
          if (data.length == trHTML.length) {
            $('#lFileList').DataTable({
              data: trHTML,
              bSort: false,
              pageLength: 4,
              columns: [{
                  title: "Name"
                },
                {
                  title: "keyword"
                },
                {
                  title: "Action"
                }
              ]
            });
          }
        }
      }
    },
    type: 'POST'
  });
}
vimal mishra
  • 1,087
  • 2
  • 12
  • 32
  • 1
    The issue is because on successive AJAX requests you're calling `DataTable()` on an element that already *is* a DataTable. You can fix this by inverting the logic so that the DataTable makes its own AJAX requests to fetch data. That way you only need to call its `reload()` method: https://datatables.net/reference/api/ajax.reload() – Rory McCrossan Jul 27 '17 at 14:03
  • ... alternatively you can use the method outlined in [this answer](https://stackoverflow.com/a/12934444/519413) to achieve what you need without too much disruption to your current logic, although it's really ugly code. – Rory McCrossan Jul 27 '17 at 14:05
  • is there any way I can destroy or draw again whenever I am calling this function. – vimal mishra Jul 27 '17 at 14:16
  • That's another alternative, although less than ideal. – Rory McCrossan Jul 27 '17 at 14:17
  • but the issue I am facing in this display is set to none automatically after destroying and recreating. – vimal mishra Jul 27 '17 at 14:55
  • Add `destroy: true` to the init attributes....This will solve the issue. – davidkonrad Jul 27 '17 at 14:59

0 Answers0