12

I am trying to achieve https://almsaeedstudio.com/themes/AdminLTE/pages/tables/data.html - "Data Table With Full Features"

When I added tbody statically, pagination and sorting works fine but when I add tbody using jquery as given below, rows are added but pagination and sorting fails.

HTML

<table id="tblItems">
    <thead>
        <tr>
            <th>code</th>
            <th>Name</th>
            <th>Description</th>
            <th>Image</th>
            <th>Parent</th>
            <th>Location</th>
            <th>Category</th>
        </tr>
    </thead>
</table>

jquery

$(document).ready(function() {
    $('#tblItems').DataTable({
        "paging": true,
        "lengthChange": false,
        "searching": false,
        "ordering": true,
        "info": true,
        "autoWidth": false,
        "sDom": 'lfrtip'
    });
    $('#tblItems').append('<tbody><tr><td>asdsa34id</td><td> asdsa34id </td><td>asdsa34id </td><td> asdsa34id</td><td>asdsa34id</td><td>asdsa34id</td><td>asdsa34id</td></tr></tbody>');
});

https://jsfiddle.net/techjerk2013/vwpsxhaL/

Updated Code

The updated code doesn't populate the table though there are data from the response. Though I set the deferRender to true, still the datatable is empty.

$(document).ready(function() {
    PopulateItemsTable();
    BindTable();
});

function BindTable() {
    $("#tblItems").DataTable({
        "deferRender": true,
        "paging": true,
        "lengthChange": false,
        "searching": false,
        "ordering": true,
        "info": true,
        "autoWidth": false,
        "sDom": 'lfrtip'
    });
}

function PopulateItemsTable() {
    var txt = "";
    $.ajax({
        type: "POST",
        url: "Item.aspx/Search",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var jsonObject = JSON.parse(response.d);
            if (jsonObject) {
                var len = jsonObject.length;
                if (len > 0) {
                    for (var i = 0; i < len; i++) {
                        if (jsonObject[i].Id) {
                            Id = jsonObject[i].Id;
                        }
                        else {
                            Id = '';
                        }
                        if (jsonObject[i].Name) {
                            Name = jsonObject[i].Name;
                        }
                        else {
                            Name = '';
                        }
                        if (jsonObject[i].Description) {
                            Description = jsonObject[i].Description;
                        }
                        else {
                            Description = '';
                        }
                        if (jsonObject[i].Image) {
                            Image = jsonObject[i].Image;
                        }
                        else {
                            Image = '';
                        }
                        if (jsonObject[i].Parent) {
                            Parent = jsonObject[i].Parent;
                        }
                        else {
                            Parent = '';
                        }
                        if (jsonObject[i].Location) {
                            Location = jsonObject[i].Location;
                        }
                        else {
                            Location = '';
                        }
                        Category = '';

                        txt += "<tr><td>" + Id + "</td><td>" + Name + "</td><td>" + Description + "</td><td>" + Image + "</td><td>" + Parent + "</td><td>" + Location + "</td><td>" + Category + "</td></tr>";
                        $('#tblItems').append('<tbody>' + txt + '</tbody>');
                    }
                }
                else {
                    $("#tblItems").append("No records found");
                }

            }
        },
        failure: function () {
            $("#tblItems").append(" Error when fetching data please contact administrator");
        }
    });
}

Answer

With the help of people answered below, the code below works as expected.

<script type="text/javascript">

    var myTable;

    $(document).ready(function () {
        BindItemTable();
        PopulateItemsTable();

    });

    function BindItemTable() {
        myTable = $("#tblItems").DataTable({
            "deferRender": true,
            "paging": true,
            "lengthChange": false,
            "searching": false,
            "ordering": true,
            "info": true,
            "autoWidth": false,
            "sDom": 'lfrtip'
        });
    }

    function PopulateItemsTable() {
        $.ajax({
            type: "POST",
            url: "ItemManagement.aspx/SearchIdList",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                var jsonObject = JSON.parse(response.d);
                var result = jsonObject.map(function (item) {
                    var result = [];
                    result.push(item.Id);
                    result.push(item.Name);
                    result.push(item.Description);
                    result.push(item.Image);
                    result.push(item.Parent);
                    result.push(item.Location);
                    result.push("");
                    return result;
                });
                myTable.rows.add(result);
                myTable.draw();
            },
            failure: function () {
                $("#tblItems").append(" Error when fetching data please contact administrator");
            }
        });
    }
</script>
1
  • How can you add multiple arrays of data using AJAX to Datatables? Commented Jun 11, 2020 at 12:43

3 Answers 3

14

Do not add the row to the table markup directly, instead add it to DataTable instance and then use the .draw() method. Adding to the DataTable instance will internally add it as a tbody anyway. Something like this should do

var mytable = $('#tblItems').DataTable({
    "paging": true,
        "lengthChange": false,
        "searching": false,
        "ordering": true,
        "info": true,
        "autoWidth": false,
        "sDom": 'lfrtip'
});
mytable.row.add(['asdsa34id', 'asdsa34id', 'asdsa34id', 'asdsa34id', 'asdsa34id', 'asdsa34id', 'asdsa34id']);
mytable.draw();

Here is a demo https://jsfiddle.net/dhirajbodicherla/vwpsxhaL/1/

Also reading how to add rows to DataTable from their documentation for further reference


Update

You can use rows.add() (plural) and do something like this

var jsonObject = JSON.parse(response.d);
var result = jsonObject.map(function(item){
  var result = [];
  result.push(item.Id); 
  // .... add all the values required
  return result;
});
myTable.rows.add(result); // add to DataTable instance
myTable.draw(); // always redraw

var myTable;
$(document).ready(function() {
  myTable = $("#tblItems").DataTable({
    "deferRender": true,
    "paging": true,
    "lengthChange": false,
    "searching": false,
    "ordering": true,
    "info": true,
    "autoWidth": false,
    "sDom": 'lfrtip'
  });
  PopulateItemsTable();
});

function PopulateItemsTable() {
  $.ajax({
    type: "POST",
    url: "Item.aspx/Search",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (response) {
      var jsonObject = JSON.parse(response.d);
      var result = jsonObject.map(function(item){
        var result = [];
        result.push(item.Id); 
        // .... add all the values required
        return result;
      });
      myTable.rows.add(result); // add to DataTable instance
      myTable.draw(); // always redraw
    }
  });
}
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you, I updated the code and facing issue in ajax call. Can you please have a look and share your thoughts?
can you share how the JSON object would look like ?
The response.d will be [{"Id":"2F2203447334C31000000006","Name":"2F2203447334C31000000006","Description":"2F2203447334C31000000006","Parent":"","Image":"","Verified":"no","State":"","Location":"","X":"0","Y":"0","Z":"0","IdClass":"User","Color":null,"Position":null} ........ ]
and you will be using all the attributes of the object?
Nope, I will not use all and I need to put an empty string when the value is null.
|
2

If you are modifying the table html using jQuery but not the apis provided by plugin then you have to call the plugin again so that it will reinstantiate as per the modified html.

$(document).ready(function() {
    $('#tblItems').append('<tbody><tr><td>asdsa34id</td><td> asdsa34id </td><td>asdsa34id </td><td> asdsa34id</td><td>asdsa34id</td><td>asdsa34id</td><td>asdsa34id</td></tr></tbody>');

    $('#tblItems').DataTable({
        "paging": true,
        "lengthChange": false,
        "searching": false,
        "ordering": true,
        "info": true,
        "autoWidth": false,
        "sDom": 'lfrtip'
    });

});

Demo https://jsfiddle.net/8hyr08xb/

Update based on the edited question

Try this

function PopulateItemsTable() {
    var txt = "";
    $.ajax({
        type: "POST",
        url: "Item.aspx/Search",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var jsonObject = JSON.parse(response.d), html = [];
            if (jsonObject) {
                var len = jsonObject.length;
                if (len > 0) {
                    for (var i = 0; i < len; i++) {
                        if (jsonObject[i].Id) {
                            Id = jsonObject[i].Id;
                        }
                        else {
                            Id = '';
                        }
                        if (jsonObject[i].Name) {
                            Name = jsonObject[i].Name;
                        }
                        else {
                            Name = '';
                        }
                        if (jsonObject[i].Description) {
                            Description = jsonObject[i].Description;
                        }
                        else {
                            Description = '';
                        }
                        if (jsonObject[i].Image) {
                            Image = jsonObject[i].Image;
                        }
                        else {
                            Image = '';
                        }
                        if (jsonObject[i].Parent) {
                            Parent = jsonObject[i].Parent;
                        }
                        else {
                            Parent = '';
                        }
                        if (jsonObject[i].Location) {
                            Location = jsonObject[i].Location;
                        }
                        else {
                            Location = '';
                        }
                        Category = '';

                        html.push("<tr><td>" + Id + "</td><td>" + Name + "</td><td>" + Description + "</td><td>" + Image + "</td><td>" + Parent + "</td><td>" + Location + "</td><td>" + Category + "</td></tr>");
                    }

                    $('#tblItems')
                       .append('<tbody>' + html.join('') + '</tbody>')
                       .DataTable({
                          "paging": true,
                          "lengthChange": false,
                          "searching": false,
                          "ordering": true,
                          "info": true,
                          "autoWidth": false,
                          "sDom": 'lfrtip'
                   });
                }
                else {
                    $("#tblItems").append("No records found");
                }

            }
        },
        failure: function () {
            $("#tblItems").append(" Error when fetching data please contact administrator");
        }
    });
}

5 Comments

Thank you, I updated the code and facing issue in ajax call. Can you please have a look and share your thoughts?
since it is a ajax response I just updated the question. The response.d will be [{"Id":"2F2203447334C31000000006","Name":"2F2203447334C31000000006","Description‌​":"2F2203447334C31000000006","Parent":"","Image":"","Verified":"no","State":"","L‌​ocation":"","X":"0","Y":"0","Z":"0","IdClass":"User","Color":null,"Position":null‌​} ........ ]. Please let me know if this will help
I see only the header
Can you log html array and see what is there in it?
Thank you, I've updated the question with working code. Thank you again.
0

Trust me, i did all the above none ever works as expected without writing long lines of code

The solution for me was pretty simple and quick. Now to get Data Table to work with your Ajax request you have to call the request first before engaging datatable Example

enter image description here

Note you don't have to call DataTable first before calling your ajax, The table needs data to be fed into the table body

<tbody class="load-transactions"> and append using jquery for the rest

enter image description here

Just try this. Thank me later.

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.