Search code examples
jqueryajaxdatatablesserver-side

DataTables Ajax handling for session expiry


Im using Datatables and server side processing for data loading.

For the current implementation the table data generates without any error unless there is an session expiry or server timeout.

I would like to handle server side exceptions and if everything is ok, the table data should load.

The below is the function

let scheduler_name  =   $("#sche_name").val().trim();

$('#monitor_scheduler_tbl').DataTable( { 
    "aoColumnDefs": [
    { 'bSortable': true, 'aTargets': [0,1,2,3] },{ "bSearchable": false,'aTargets': [-1] }], 
    "processing": true,
    "bDestroy": true,
    "bFilter":false,
    "serverSide": true,
    "ajax": {
        "url": config.yaws_file_path + "css_monitor_scheduler.yaws",
         "data": function ( d ) {
            d.action            = "SEARCH_SCHEDULER",
            d.scheduler_name    = scheduler_name;
        },
        "complete": function(response){

            res = JSON.parse(response.responseText);

            if(error = res['err'])
            {
                objApp.showToastMessage('error', error);
            }
        }
    }
});

Solution

  • On the server side, you should respond with HTTP error codes to different situations.

    On the client side, you can define an ajax error handler to dataTables that recognizes these response codes:

    "ajax": {
      "error" = function (jqXHR, textStatus, error) {
        if (jqXHR && jqXHR.status == 440) {
          // Session expired - do something here
        } else if (jqXHR && jqXHR.status == 408) {
          // Request timeout - do something here
        } else {
          // Some other error - do something here
        }
      }