Ask the user if he wants to leave current view (prevent to page/search away from current displayed)

Ask the user if he wants to leave current view (prevent to page/search away from current displayed)

marcosdimitriomarcosdimitrio Posts: 8Questions: 2Answers: 0

I have a data table with a custom form based on the data displayed. The user might fill some data and forget to save it, and then when he pages/searches away, all data is lost. I want to display a simple confirmation dialog, telling him that he will lose all changes. How can I do that?

I have tried attaching an event handler to the paging buttons like below, it executes after the paging and doesn't cancel it.

$(document).on('click', '.paginate_button', function(e) {
    e.stopPropagation();
    e.preventDefault();
    return false;
});

I have also tried to attach an event handler to preXhr, but I couldn't cancel the ajax call:

$('#myTable')
.on('preXhr.dt', function ( e, settings, data ) {
    var table = new $.fn.dataTable.Api( settings );
    if (table.settings()[0].jqXHR) {
        table.settings()[0].jqXHR.abort();
    }
});

I could use a custom ajax handler, but it would be a lot of work and waste of built-in functionality for a simple thing.

$("#example").dataTable({
    // ...
    "ajax": getRows()
});

function getRows() {
    return function ( request, drawCallback, settings ) {
        // ...
    };
}

Any ideas? Is there an easier way to prevent any state change in DataTables?

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,552Questions: 1Answers: 10,477 Site admin
    Answer ✓

    The preDrawCallback callback option might be what you want.

    Allan

  • marcosdimitriomarcosdimitrio Posts: 8Questions: 2Answers: 0
    edited July 2015

    That's exactly what I needed, as it stops Datatables from sending the AJAX request. Thanks a lot!

  • marcosdimitriomarcosdimitrio Posts: 8Questions: 2Answers: 0
    edited July 2015

    By the way, couldn't this be a feature of preXhr as well, when it receives return false? It seems to me like the right place to look for such feature, i.e., stopping an AJAX request before it happens.

  • allanallan Posts: 63,552Questions: 1Answers: 10,477 Site admin

    Yes it possibly could be - but currently isn't. I plan to review the options for cancelling a draw in future.

    Allan

This discussion has been closed.