Rohin Rohin - 4 months ago 38
Ajax Question

Bootstrap datatable not working after loading data using ajax json

I'm loading data dynamically to html table as below
Technology stack used is: Spring MVC Hibernate Ajax JQuery
But the datatable functionalities are not responding

function getdata()
{
$.ajax({

type: "GET",
url: "/controllerURL.html", //controller URL
contentType: "application/json; charset=utf-8",
dataType: "json",

success: function (results) {
console.log(results)
var success = results.success;
if(success){
var finaldata = "<tbody><thead><tr><th>ID</th><th>data1</th><th>data2</th><th>Update</th></tr></thead>"; //data
var data = results.message;
data = jQuery.parseJSON(data);
alert(data);
for(var i = 0; i < data.length; i++){
var value = data[i];
finaldata = finaldata+ "<tr><th>"+value.ID+"</th><th>"+value.variable1+"</th><th>"+value.variable2+"</th></tr>";
}
finaldata = finaldata + "</tbody>";
$("#tableID").html(finaldata);
$("#tableID").DataTable();//re-intializing datatable
}
},
error: function (data) {
alert("fail");
console.log('ajax call error');

}
});
}


After this datatable functionalities are not working

Answer

You need to have proper table structure with <thead></thead> and <tbody></tbody>. Also number of th elements should match number of td elements.

Assuming that other parts of your code work correctly, use the code below instead:

function getdata() {
    $.ajax({
        type: "GET",
        url: "/controllerURL.html", //controller URL
        contentType: "application/json; charset=utf-8",
        dataType: "json",

        success: function(results) {
            console.log(results)
            var success = results.success;
            if (success) {
                var finaldata = "<thead><tr><th>ID</th><th>data1</th><th>data2</th><th>Update</th></tr></thead><tbody>"; //data
                var data = results.message;
                data = jQuery.parseJSON(data);
                alert(data);
                for (var i = 0; i < data.length; i++) {
                    var value = data[i];
                    finaldata = finaldata + "<tr><td>" + value.ID + "</td><td>" + value.variable1 + "</td><td>" + value.variable2 + "</td><td></td></tr>";
                }
                finaldata = finaldata + "</tbody>";
                $("#tableID").html(finaldata);
                $("#tableID").DataTable();
            }
        },
        error: function(data) {
            alert("fail");
            console.log('ajax call error');

        }
    });
}