简体   繁体   中英

ajax success function not working on datatable

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/

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

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/

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM