skip to Main Content

I have read the datatables.net documentation on populating a datatable using ajax and can’t get anywhere.

FROM THE CONTROLLER USING ASP.NET Core, the following method:

[HttpGet ("EmployeesJSON")]
public JsonResult EmployeesJSON()
{
   var AllEmployees = _iEmployeeService.GetAllEmployees();
   var json = JsonConvert.SerializeObject(AllEmployees, Formatting.Indented);
   return new JsonResult(json);
}

Result returned from controller:
enter image description here

FROM Javascript using AJAX

var _data;
$(document).ready(function () {
        $.ajax({
            type: $(this).attr('GET'),
            url: "Employees/EmployeesJSON", 
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) { // on success..            
                _data = response;
                initDataTable(); //initialize the data table
            }
        }); 
    });

What data looks like from AJAX call
enter image description here

initDataTable() is called if success from AJAX Call

function initDataTable() {
       var employeeTable = $('#employee_table').DataTable(
        {
            scrollX: true,
            scrollY: 400,
            data: _data, 
            columns: [
                { sName: "LastName", data: "LastName", bSearchable: true, bSortable: false }
            ],
            lengthMenu: [[25, 50, -1], [25, 50, 'All']],            
        });
}

Error message from datatables.net

Error message from datatables.net

3

Answers


  1. Chosen as BEST ANSWER

    I'm placing this here in case someone else runs into this.

    I was referencing a column with the wrong field name. Make sure your column names match! Final AJAX and datatable init:

     (document).ready(function () {
            var editLink = '<a class="editLink"><span class="fa-stack fa-lg" style="font-size:.8em;color:green;"><i class="fa fa-circle fa-stack-2x"></i><i class="fa fa-arrow-right fa-stack-1x fa-inverse"></i></span></a>';
            var employee_table = $('#employee_table').DataTable({
                //scroll x and y are required to keep make the header scroll on horizontal
                scrollY: 600,
                scrollX: true,
                ajax: {
                    url: 'Employees/EmployeesJSON',
                    dataSrc: '',
                },
                columns: [
                    { data: null, defaultContent: editLink, sortable: false },
                    { data: "EmployeeName", searchable: true, sortable: true },
                    { data: "ForemanName", searchable: true, sortable: true },
                    { data: "SeniorityCode", searchable: true, sortable: true, className: 'text-center' },
                    { data: "JobCode", searchable: true, sortable: true },
                    { data: "DateAssigned", searchable: true, sortable: true },
                    { data: "OvertimeGroupDescription", searchable: true, sortable: true },
                    { data: "ScheduleGroup", searchable: false, sortable: true, className: 'text-center' },
                    { data: "AdjustedHours", searchable: false, sortable: true, className: 'text-center' },
                    { data: "OvertimeRefusal", searchable: false, sortable: true, className: 'text-center' },
                    { data: "DateHired", searchable: false, sortable: true },
                    { data: "DateTerminated", searchable: true, sortable: true }
                ],
                order: [ [11, 'asc'],[1, 'asc']],
                "fnDrawCallback": function () {
                    $('table#employee_table td').bind('mouseenter', function () { $(this).parent().children().each(function () { $(this).addClass('datatablerowhighlight'); }); });
                    $('table#employee_table td').bind('mouseleave', function () { $(this).parent().children().each(function () { $(this).removeClass('datatablerowhighlight'); }); });
                },
                lengthMenu: [[25, 50, -1], [25, 50, 'All']],  
                initComplete: function () {
                    this.api()
                        .columns()
                        .every(function () {
                            var column = this;
                            //add drop downs only to foreman, overtime group
                            if (column.index() == 2 || column.index() == 6) {
                                var select = $('<br/><select><option value=""></option></select>')
                                    .appendTo($(column.header()))
                                    .on('change', function () {
                                        var val = $.fn.dataTable.util.escapeRegex($(this).val());
                                        column.search(val ? '^' + val + '$' : '', true, false).draw();
                                    });
                                column
                                    .data()
                                    .unique()
                                    .sort()
                                    .each(function (d, j) {
                                        select.append('<option value="' + d + '">' + d + '</option>');
                                    });
                            }
                        });
                }
            });
            //edit individual record event
            $('#employee_table tbody').on('click', '.editLink', function () {
                var data = employee_table.row($(this).parents('tr')).data();
                document.location.href = 'Employees/' + data['PN'];
            });
        });
    

  2. you have to put the names in quotes

    columns: [
              {"title": "LastName", "data": "LastName", "bSearchable": true, "bSortable": false }
             ],
    

    if you still have some problems, you can try a camel case

      ... "data": "lastName",...
    
    Login or Signup to reply.
  3. Here is a demo using the suggestions I made in my comments:

    <!doctype html>
    <html>
    <head>
      <meta charset="UTF-8">
      <title>Demo</title>
      <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
      <script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.js"></script>
      <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.css">
      <link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">
    
    </head>
    
    <body>
    
    <div style="margin: 20px;">
    
        <table id="example" class="display dataTable cell-border" style="width:100%">
        </table>
    
    </div>
    
    <script>
    
    $(document).ready(function() {
    
      var table = $('#example').DataTable( {
        scrollX: true,
        scrollY: 400,
        ajax: {
          url: 'Employees/EmployeesJSON',
          dataSrc: '',
        },
        columns: [
          { 
            title: "Last Name",
            name: "LastName",
            data: "LastName", 
            searchable: true, 
            sortable: false 
          },
          { 
            title: "First Name",
            name: "FirstName",
            data: "FirstName", 
            searchable: true, 
            sortable: false 
          } //,
          // add more columns here...
        ],
        lengthMenu: [[25, 50, -1], [25, 50, 'All']]
      } );
    
    } );
    
    </script>
    
    </body>
    </html>
    

    It assumes your Ajax call returns JSON like the following:

    [
      {
        "PN": "149458",
        "FirstName": "MICHAEL",
        "LastName": "ADAMS",
        "DateHired": "2016-02-01",
        "DateTerminated": null
      },
      {
         //... another row of data here
      },
      ...
    ]
    

    Notes:

    1. My sample JSON only contains 5 fields per record – your JSON contains more, of course.

    2. My DataTable only uses 2 of my 5 fields – but you can extend my code to add more fields, as needed. See the columns: section of the code.

    3. I have used the DataTables built-in support for Ajax (it makes the code simpler, in my opinion, but you can still use an external Ajax call if you prefer).

    4. Because your JSON uses an unnamed array (according to the screenshot in your question), you need to use dataSrc: ''. This tells DataTables where the array can be found in your JSON.

    In contrast, if you had JSON that looked like this (just as an example):

    
    {
      "foo": [
        {
          "PN": "149458",
          "FirstName": "MICHAEL",
          "LastName": "ADAMS",
          "DateHired": "2016-02-01",
          "DateTerminated": null
        },
        {
           //... another row of data here
        },
        ...
      ]
    }
    

    …then you would need to use dataSrc: 'foo' because that is where the array of objects is located in the JSON

    1. Instead of using variables such as sName and bSearchable, I use the modern versions name, searchable and so on. The older names still work.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search