Dom
Dom

Reputation: 159

Adding JSON data to DataTable

Hoping someone can access this for me cause I cannot figure it out.

The data is successfully being received, however the data won't load into the table. There's no error message. It just simply won't do it. This worked previously when I used an ajax call within the DataTable, but when I move the Ajax call outside of the DataTable creation then it does not work.

Example JSON data:

{
    "data":[
        {
            "Id": 1,
            "Name": "Fred"
        },
        {
            "Id": 2,
            "Name": "Tommy"
        }
    ]
}

Function call to get JSON:

function getJSON() {
    $.ajax({
        url: "Home/GetList",
        type: "GET",
        datatype: "json"
    }).done(function(data) {
        drawDataTable('Table', data);
    });
}

Drawing the DataTable

function drawDataTable(divId, data) {
    var table = $('#' + divId).DataTable({
        data: data,
        dataSrc: "",
        columnDefs: [
            { "targets": [0], "data": "Id" },
            { "targets": [1], "data": "Name" }
        ]
    });
    return table;
}

I then send this large array of data (1000 array elements) to my Datatable function via function drawDataTable(divId, data)

And within that DataTable function I use:

data: data,
dataSrc: ""

I have also tried removing the dataSrc and also making it dataSrc: "data" but neither worked.

Upvotes: 0

Views: 84

Answers (2)

seth_007
seth_007

Reputation: 38

I think you missed the structure of JSON, please try data.data

 function drawDataTable(divId, data) {
        var table = $('#' + divId).DataTable({
            data: data.data, //updated here
            dataSrc: "",
            columnDefs: [
                { "targets": [0], "data": "Id" },
                { "targets": [1], "data": "Name" }
            ]
        });
        return table;
    }

Upvotes: 2

Al Masum Fahim
Al Masum Fahim

Reputation: 113

Make sure you are writing your code inside this function

$(document).ready(function() { 
// your code
}

because anything written outside this, might not work properly, specially when you are working with dataTables.

Also, you can write this code in the following way ( if this helps )

$(document).ready(function() {
   function drawDataTable(divId,data) {
   var t = $('#'+ divId).DataTable();
   var dataObj = JSON.parse(data);
   dataObj.forEach(element => {
      t.row.add([
            element.Id,
            element.name
         ]).draw(false)
    });
 }})

Upvotes: 0

Related Questions