Search code examples
javascriptjqueryajaxdatatablesjquery-datatables-editor

How to use Editor from DataTables and call data from ajax


I have a database of lots of info that build the table. What I want to be able to do is load the data through the ajax call and then be able to edit the data in the table. But I can't get the data to show up on the page. I'm using the DataTables in another interface and the loading, sorting, and other cool features work. I haven't used Editor before and I'm a little confused.

function drawDataTable(){
   var len = allocationData.length;
     html = "<div id='dataTableDiv'><table id='dataTable' class='table table-bordered table-striped dataTable' role='grid'><thead><tr role='row'><th>System Name</th><th>Gatherer</th><th>Operator</th><th>County</th><th>Sample Date</th><th>Daily Avg</th></tr></thead><tbody>";
   for (i=0;i<len;i++){
     html += "<tr><td>" + allocationData['SystemName'][i] + "</td><td>" + allocationData['Gatherer'][i] + "</td><td>" + allocationData['Operator'][i] + "</td><td>" + allocationData['County'][i] + "</td><td>" + allocationData['SampleDate'][i] + "</td><td>" + allocationData['DailyAvg'][i] + "</td></tr>";

   }
   html += "</tbody></table></div>";

  $(".table-responsive").html(html);
}

$(function(){
  editor = new $.fn.dataTable.Editor( {
    "ajax": "qry/dataTable.php",
    "table": "#dataTable",
    "fields":[{
        "name": "SystemName"
    },{
        "name": "Gatherer"
    },{
        "name": "Operator"
    },{
        "name": "County"
    },{
        "name": "SampleDate"
    },{
        "name": "DailyAvg"
    }]
});

$('#dataTable').DataTable({
    dom: "Bfrtip",
    ajax: {
        type: "POST",
        url: "qry/dataTable.php",
        success: function(){
            drawDataTable();
        }
    },
    serverSide: true,
   columns: [
        {data: "SystemName"},
        {data: "Gatherer"},
        {data: "Operator"},
        {data: "County"},
        {data: "SampleDate"},
        {data: "DailyAvg"}
    ],
    select: true,
    buttons: [
        { extend: "create", editor: editor },
        { extend: "edit",   editor: editor },
        { extend: "remove", editor: editor }
    ]
  });
});

Solution

  • Try editing your success: function. See if this helps.

            success: function(result){
                allocationData = JSON.parse(result);
                drawDataTable();
             }