Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataTables ajax.reload() loses page

I am using jQuery DataTables. After ajax request, I call the ajax.reload() method to refresh my dataTable but I lose the current page. It returns the first page.

Here is my DataTables init:

datatable_appointments = $('#datatable_appointments').DataTable({
    "responsive" : true,
    "processing" : true,
    "serverSide": true,
    "bSort" : false,
    "ajax": function(data, callback, settings) {
        // make a regular ajax request using data.start and data.length
        $.get(URL_API + URL_APPOINTMENTS_STATE + '/', {
            limit: data.length,
            offset: data.start,
            search: data.search.value
        }, function(res) {
            if (res.error) {
                callback({
                    recordsTotal: 0,
                    recordsFiltered: 0,
                    data : ""
                });
            } else {
                data_appointments = res.data;
                // map your server's response to the DataTables format and pass it to
                // DataTables' callback
                callback({
                    recordsTotal: res.total_data,
                    recordsFiltered: res.total_data,
                    data: res.data
                });
                $("#datatable_appointments > tbody > tr > td").addClass("text-center");
                $("#datatable_appointments > tbody > tr > td").css("vertical-align", "middle");
                $("#datatable_appointments > thead > tr > th").addClass("text-center");
            }
        });
    },
    "columns" : [
        { "data": "service_name"},
        { "data": "doctor_info"},
        { "data": "patient_name", render: function (data, type, row, meta) {
            return row.name + " " + row.surname;
        }},
        { "data": "appointment_date", render: function (data, type, row, meta) {
            var formattedDate = new Date(row.appointment_date);
            var day = formattedDate.getDate();
            var month =  formattedDate.getMonth();
            var hours = (formattedDate.getHours().toString().length == 1) ? '0' + formattedDate.getHours() : formattedDate.getHours();
            hours += ':';
            hours += (formattedDate.getMinutes().toString().length == 1) ? formattedDate.getMinutes() + '0' : formattedDate.getMinutes();
            return day + ' ' + months[month] + ', ' + hours;
        }},
        { "data": "state", render: function (data, type, row, meta) {
            if (row.state == '0')
                return '<i class="fa fa-circle font-red-mint"></i><br />İptal';
            else if (row.state == '1')
                return '<i class="fa fa-circle font-green-jungle"></i><br />Onaylı';
            else if (row.state == '2')
                return '<i class="fa fa-circle font-grey-salsa"></i><br />Beklemede';
        }},
        { "data": "actions", render: function (data, type, row, meta) {
            if (row.state == '2')
                return '<div class="btn-group btn-group-circle">' +
                            '<button type="button" onclick="setState(\''+row.id+'\', \'1\');" class="btn btn-outline green btn-sm">Onayla</button>' +
                            '<button type="button" onclick="setState(\''+row.id+'\', \'0\');" class="btn btn-outline red btn-sm">İptal Et</button>' +
                        '</div>';
            else
                return '';
        }}
    ],
    "sPaginationType": "full_numbers",
    "language": {
        "emptyTable": "Kayıt bulunamadı.",
        "sZeroRecords": "Bu kriterde sonuç bulunamadı.",
        "search": "Bul",
        "sProcessing" : "<img src='/assets/global/img/loading-spinner-blue.gif' />",
        "sInfo": "Toplam <b>_TOTAL_</b> veri bulunmaktadır.",
        "sLengthMenu": "Gösterilen kayıt sayısı _MENU_",
        "sInfoFiltered": "",
        "sInfoEmpty":"",
        "paginate": {
            "sPrevious": "Önceki",
            "sNext": "Sonraki",
            "sFirst" : "İlk",
            "sLast" : "Son"
        }

    }
});

And my setState method in same js file:

function setState(id, state) {
    $.ajax({
        url : URL_API + URL_APPOINTMENTS_STATE + '/' + id,
        type : 'put',
        data : {'state' : state},
        dataType : 'json',
        success : function (response) {
            if (response.error) {

            } else {
                datatable_appointments.ajax.reload();
            }
        }
    });
}
like image 607
Nevermore Avatar asked Mar 20 '17 13:03

Nevermore


People also ask

How do you redraw the data table without loosing the current page?

remove(). draw( false ); Documentation here false - the ordering and search will be recalculated and the rows redrawn in their new positions. The paging will not be reset - i.e. the current page will still be shown.

What does Ajax reload do?

Description. In an environment where the data shown in the table can be updated at the server-side, it is often useful to be able to reload the table, showing the latest data. This method provides exactly that ability, making an Ajax request to the already defined URL (use ajax.

What is stateSave in DataTables?

When DataTables' state saving option is enabled ( stateSave ) KeyTable will automatically store the last cell focused in a table and then restore that state when the page is reloaded.

How much data can DataTables handle?

The maximum number of rows that a DataTable can store is 16,777,216.


Video Answer


2 Answers

You need to pass parameters for keeping current page like:

datatable_appointments.ajax.reload( null, false )

source: https://datatables.net/reference/api/ajax.reload()

like image 108
shaile Avatar answered Oct 24 '22 05:10

shaile


  $(document).ready(function() {
        $('#table_id').DataTable( {
            stateSave: true
        } );
    });

Anyone who are using jQuery DataTables and wants to perform tasks e.g. reload the page, or edit, delete, will face a problem to lose the current page and navigate to 1st page, this snippet will help him to stay on the same page, It avoids to return from current page to first page.

like image 4
shubham kumar Avatar answered Oct 24 '22 05:10

shubham kumar