Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataTables Dynamic displayStart

I'm trying to get my javascript to use a dynamic value for "displayStart". I'm getting the data from a php script that returns JSON. Here is my js:

    balance.list = function () {
    $('#balance').dataTable({
        processing: true,
        ajax: {
            url: 'php/list.php',
            dataSrc: 'data'
        },
        dom: '<"top"flp<"clear">>rt<"bottom"ip<"clear">>',
        pageLength: 50,
        autoWidth: false,
        displayStart: '100',

        columns: [
        {
            width: "10%",
            data: "date"
        }, {
            width: "5%",
            data: "checknum"
        }, {
            width: "75%",
            data: "description"
        }, {
            width: "5%",
            data: "debit"
        }, {
            width: "5%",
            data: "credit"
        }, {
            width: "5%",
            data: "balance"
        }]
    });
};

instead of displayStart: '100', I want it be something like: displayStart: displayStart.displayStart,

But I'm setting the dataSrc to data, which is another branch of the JSON

And here is the JSON data:

{
  "displayStart":"100",
  "data": [
  {
    "date":"2015-03-27",
    "checknum":null,
    "description":null,
    "debit":"50.00",
    "credit":"0.00",
    "balance":"500.00"
  },
  {
    "date":"2015-03-28",
    "checknum":null,
    "description":null,
    "debit":"0.00",
    "credit":"250.00",
    "balance":"750.00"
  }
  ]
}

I've messed around with the ajax portion using a success/error function, but then it doesn't continue on to finish the table.

How do I set the value?

like image 670
James Avatar asked Apr 25 '26 13:04

James


1 Answers

You can change the page after the data has been loaded by adding two event handlers after you DataTables initialization code as shown below.

// Handles DataTables AJAX request completion event
$('#balance').on('xhr.dt', function( e, settings, json){
   $(this).data('is-loaded', true);
});

// Handles DataTables table draw event
$('#balance').on('draw.dt', function (){
   if($(this).data('is-loaded')){
      $(this).data('is-loaded', false);
      var api = $(this).DataTable();
      var json = api.ajax.json();
      var page_start = json['displayStart'];

      // Calculate page number
      var page = Math.min(Math.max(0, Math.round(page_start / api.page.len())), api.page.info().pages);

      // Set page
      api.page(page).draw(false);
   }
});
like image 170
Gyrocode.com Avatar answered Apr 28 '26 03:04

Gyrocode.com



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!