Question: ajax success function not working on datatable

Question

ajax success function not working on datatable

Answers 3
Added at 2016-12-29 12:12
Tags
Question

I'm using datatable to show list from database mysql

I need to update some input on end of table loading, then I'm using success function but this seems to prevent data rendering

var table = $('#example').DataTable({
'processing': true,
'serverSide': true,
'ajax': {
  type: 'POST',
  'url': url,
  'data': function (d) {
    console.log(d.order);
    return JSON.stringify( d );
  },

  // EDIT this "my" success function
  success: function( data ) {
    $('#my_input').val(data.return);
  }
}

Json returned is:

{
 "data":[[ (datatable value) ]],
 "returned":"myvalue"
}

here the jsfiddle

EDIT http://jsfiddle.net/ntcwust8/95/

Answers
nr: #1 dodano: 2016-12-29 12:12

Just remove the success callback.

success - Must not be overridden as it is used internally in DataTables. To manipulate / transform the data returned by the server use ajax.dataSrc (above), or use ajax as a function

Datatable by default handles the success callback, Don't override it.

Instead use complete option of AJAX to do something after data loading.

Updated fiddle

nr: #2 dodano: 2016-12-29 12:12

You just need to remove success callback.

var table = $('#example').DataTable({
        'processing': true,
        'serverSide': true,
        'ajax': {
          type: 'POST',
          'url': url,
          'data': function (d) {
            console.log(d.order);
            return JSON.stringify( d );
          }
        }

Edit

you need to use ajax.dataSrc property it will call after ajax finish. It will work on refresh as well https://datatables.net/reference/option/ajax.dataSrc

var table = $('#example').DataTable({
    'ajax': {
      type: 'POST',
      'url': url,
      'data': function (d) {
        console.log(d.order);
        return JSON.stringify( d );
      },
      "dataSrc": function (json) {
       $("#mydata").val(json.recordsTotal);
       return json.data;
        }
    },

  });

here is updated fiddle. http://jsfiddle.net/2jkg3kqo/2/

nr: #3 dodano: 2016-12-29 12:12

Datatable has its own complete event thats called initComplete.

If you redefine success you are overriding Datatable's own function.

var table = $('#example').DataTable({
    'processing': true,
    'serverSide': true,
    'ajax': {
    ....
    ....
    },    
   'initComplete':function(settings, json){
        alert($('#example tbody tr').length+ ' records on screen');
 });

Reference: https://datatables.net/reference/option/initComplete

Update fidle: http://jsfiddle.net/ntcwust8/94/

Source Show
◀ Wstecz