Search code examples
javascriptajaxdatatable

Datatable : How to call async function after ajax call


I want to manipulate the data after receiving it from the server in Datatable. Data comes from the web server. But the response data from server is encoded. To decode the data I need to call another asynchronous function (here decodeData() ). I tried to call async funtion in dataSrc section like following example but data is not displayed in the table.

$(document).ready(function () {
    $('#example').DataTable({
        processing: true,
        serverSide: true,
       "ajax": {
    "url": "http://localhost:3000",
    "dataSrc": async function ( json ) { // I added async
      // call async funtion here
       json.data = await decodeData(json)
      return json.data;
    }
    });
});

Then I tried to using the xhr event, but it didn't work properly.

var table = $('#example')
          .on('xhr.dt', async function ( e, settings, json, xhr ) {  // added async
                json = await decodeData(json);
    } ).DataTable({
        processing: true,
        serverSide: true,
        "ajax": {
            "url": "http://localhost:3000",
                           },
    });

As far as I understand Datatable event handlers don't expect async functions - so they don't wait for the Promise to complete. How can I call the asynchronous function before the table is drawn?


Solution

  • I found the solution and it works for me.

          $('#example').DataTable({
        processing: true,
        serverSide: true,
        ajax: function (data, callback, settings) {
    $.ajax({
      url: 'http://localhost:3000/',
      data: data,
       success:async function(data){
       data = await decodeData(data);
     
        callback(data);
     
      }
    });