54

Is that possible to invoke a javascript function in success of datatable ajax call. Here is the code am trying to use,

var oTable = $('#app-config').dataTable(
            {
                "bAutoWidth": false,                                                
                "bDestroy":true,
                "bProcessing" : true,
                "bServerSide" : true,
                "sPaginationType" : "full_numbers",
                "sAjaxSource" : url,                    
                "fnServerData" : function(sSource, aoData, fnCallback) {
                    alert("sSource"+ sSource);
                    alert("aoData"+ aoData);
                    $.ajax({
                        "dataType" : 'json',
                        "type" : "GET",
                        "url" : sSource,
                        "data" : aoData,
                        "success" : fnCallback
                    });
                }

is it possible to have something like,

success : function(){
    //.....code goes here
}

instead of "success" : fnCallback ------> which is last line of AJAX call. In this function I would like to check a value send from server side.

starball
  • 20,030
  • 7
  • 43
  • 238
rajan.tsm
  • 541
  • 1
  • 4
  • 4
  • It is possible. Have you already tried? – John Dvorak Apr 03 '13 at 11:52
  • You are passing the argument to `FnServerData` as a callback to `$.ajax`. What would you like to use instead? – John Dvorak Apr 03 '13 at 11:56
  • Thanks for you response Dvorak. function fnCallback(){ alert("fnCallback"); } I try to call this method. So I pass callback as argument into FnserverData. If it is not passed into FnServerData it keeps on processing without reporting any error. – rajan.tsm Apr 03 '13 at 12:05
  • 2
    I tried `success : function(){ //.....code goes here }` inside this function I gave alert. And I got the alert message properly. but datatable did not load – rajan.tsm Apr 03 '13 at 12:11
  • Then you have a different issue than how to do something on ajax success. – John Dvorak Apr 03 '13 at 12:34
  • rajan.tsm: I have the same issue... the ajax.success callback seems to keep the success to itself. I've tried return true/false/data... no luck. dont' know how to pass the data on to dataTable – Brad Kent Aug 25 '15 at 13:57

10 Answers10

76

You can use dataSrc :

Here is a typical example of datatables.net

var table = $('#example').DataTable({
    "ajax": {
            "type" : "GET",
            "url" : "ajax.php",
            "dataSrc": function ( json ) {
                //Make your callback here.
                alert("Done!");
                return json.data;
            }       
    },
    "columns": [
            { "data": "name" },
            { "data": "position" },
            { "data": "office" },
            { "data": "extn" },
            { "data": "start_date" },
            { "data": "salary" }
        
        ]
    } );
Joseph Garrone
  • 1,662
  • 19
  • 20
48

You can use this:

"drawCallback": function(settings) {
   console.log(settings.json);
   //do whatever  
},
AnasSafi
  • 5,353
  • 1
  • 35
  • 38
  • Perfect here using DataTables 1.10.10, Jquery 2.1.1. – aspadacio Jan 15 '18 at 17:31
  • Thanks a lot @AnasSafi I was struggling with this from yesterday. I tried to call additional javascripts on input fields in rows for calculations purpose and used `"initComplete"` but this did not worked but `"drawCallback"` saved my day. – Muhammad Tarique Jan 25 '18 at 05:31
  • 2
    This is the solution to the problem, especially if you use server-side processing for the dataTable draws. – Mihail Minkov Mar 13 '19 at 17:28
  • Anyone who is facing issues, update your DataTables to the latest version and use "drawCallback" to make it work, simple life saving function. Thanks. – SuKu Aug 07 '19 at 11:00
  • Thanks buddy. Previously I wrote a nasty piece code ( setting timeout to call a function :'D ) to call a function after ajax data-table load. This solution saved my day and I got rid of that nasty code. This is the best solution so far. – fahim152 Jan 07 '20 at 05:27
  • and how to distuingish between success and error? I tried normal function sucess and error but doesn;t work, any hints? – Arie Jan 01 '22 at 19:57
43

The best way I have found is to use the initComplete method as it fires after the data has been retrieved and renders the table. NOTE this only fires once though.

$("#tableOfData").DataTable({
        "pageLength": 50,
        "ajax":{
            url: someurl,
            dataType : "json",
            type: "post",
            "data": {data to be sent}
        },
        "initComplete":function( settings, json){
            console.log(json);
            // call your function here
        }
    });
Chris
  • 811
  • 8
  • 17
  • 1
    yeah that worked i needed to aply datetime picker on textbox in jquery datatable, so i have to add this after all the rows are rendered on page, – Dragon Oct 31 '17 at 08:16
  • 3
    Except if you refresh the table, the initComplete is never called again because it has already been initialized. – LarryBud Jan 20 '18 at 03:54
  • if you use dataTable.draw(), this function won't work. use dataSrc in ajax instead. – fudu May 17 '19 at 03:24
  • Imho this function requires the editor! See: Editor initialisation complete event. Please note - this property requires the Editor extension for DataTables. https://editor.datatables.net/reference/event/initComplete – Harm Aug 20 '19 at 13:55
  • @Harm I have linked to the function documentation in the base version of Datatables in my answer. I do not use the editor extension. The answer by AnasSafi below seems to work better in some instances. – Chris Aug 20 '19 at 15:20
17

This works fine for me. Another way don't work good

                'ajax': {
                    complete: function (data) {
                        console.log(data['responseJSON']);
                    },
                    'url': 'xxx.php',
                },
Gianluca Demarinis
  • 1,964
  • 2
  • 15
  • 21
  • 1
    Interesting. I came here to get the syntax for 'success', but turns out that happens before the table is populated. 'Complete' worked perfectly. – BWhite Aug 05 '21 at 04:37
6

For datatables 1.10.12.

$('#table_id').dataTable({
  ajax: function (data, callback, settings) {
    $.ajax({
      url: '/your/url',
      type: 'POST',
      data: data,
      success:function(data){
        callback(data);
        // Do whatever you want.
      }
    });
  }
});
Khalid
  • 332
  • 3
  • 4
3

The success option of ajax should not be altered because DataTables uses it internally to execute the table draw when the data load is complete. The recommendation is used "dataSrc" to alter the received data.

fgfernandez0321
  • 197
  • 1
  • 5
3

Based on the docs, xhr Ajax event would fire when an Ajax request is completed. So you can do something like this:

let data_table = $('#example-table').dataTable({
        ajax: "data.json"
    });

data_table.on('xhr.dt', function ( e, settings, json, xhr ) {
        // Do some staff here...
        $('#status').html( json.status );
    } )

ako
  • 2,000
  • 2
  • 28
  • 34
1

Maybe it's not exactly what you want to do, but using the ajax complete solved my problem of hiding a spinner when the ajax call returned.

So it would look something like this

var table = $('#example').DataTable( {
    "ajax": {
            "type" : "GET",
            "url" : "ajax.php",
            "dataSrc": "",
            "success": function () {
                alert("Done!");
            }       
    },
    "columns": [
            { "data": "name" },
            { "data": "position" },
            { "data": "office" },
            { "data": "extn" },
            { "data": "start_date" },
            { "data": "salary" }            
        ]
    } );
Jonny
  • 1,037
  • 7
  • 15
1

As per the question, I think the following should suffice:

 'ajax': {
              complete: function (data) {
               console.log(data['responseJSON']);
             },
                
            },
Codeparl
  • 300
  • 1
  • 8
-1

Try Following Code.

       var oTable = $('#app-config').dataTable(
        {
            "bAutoWidth": false,                                                
            "bDestroy":true,
            "bProcessing" : true,
            "bServerSide" : true,
            "sPaginationType" : "full_numbers",
            "sAjaxSource" : url,                    
            "fnServerData" : function(sSource, aoData, fnCallback) {
                alert("sSource"+ sSource);
                alert("aoData"+ aoData);
                $.ajax({
                    "dataType" : 'json',
                    "type" : "GET",
                    "url" : sSource,
                    "data" : aoData,
                    "success" : fnCallback
                }).success( function(){  alert("This Function will execute after data table loaded");   });
            }
Zabith Rafeek
  • 79
  • 1
  • 3