Search code examples
javascriptjqueryajaxdatatablesjquery-datatables-editor

Error populating a jQuery datable with a JSON object


                       var resultTable = $('#templateRegArea').DataTable({

                            "columns": [
                                { data: "ID" },
                                { data: "Name" },
                                { data: "Description" },
                            ],
                        });
                        resultTable.rows.add(response.d).draw();
                        dataSet = response.d;

I am trying to bind a table 'templateRegArea' with the values present in "response.d" in a Jquery datatable.

response.d enter image description here

I have attached the value of "response". The problem I am facing is the data are not getting loaded into the table. HELP :(


Solution

  • Your server-side script produces objects, when jQuery DataTables requires array of arrays or array of objects. For example:

    {
        "d": [{
            "ID": "1",
            "Name": "John",
            "Description": "Test"
        }, {
            "ID": "2",
            "Name": "Bob",
            "Description": "Test"
        }]
    }
    

    When you correct the data structure as shown below, initialization code should be changed to:

    var resultTable = $('#templateRegArea').DataTable({
       "data": response.d,
       "columns": [
          { "data": "ID" },
          { "data": "Name" },
          { "data": "Description" }
       ]
    });
    

    With the existing data structure you can use the code below, but that is only good for one data row.

    var resultTable = $('#templateRegArea').DataTable({
       "data": [response.d],
       "columns": [
          { "data": "ID" },
          { "data": "Name" },
          { "data": "Description" }
       ]
    });