Show custom error messages from server side

    function init_dt(){
        datatable = $t.on('xhr.dt', function ( e, settings, json, xhr ) {
            console.log(json);
            alert(json.message);
        })
        .DataTable({
            "searching": true,
            "info": true,
            "lengthChange": true,
            "paging": true,
            'serverSide': true, 
            'processing': true, 
            "ajax": {
                'url': base_url + 'admin/ajax/' + app_key + 's',
                'data': function(d){
                    var $c = $('.buttons_panel');
                    d.exam_type = get_value('exam_type', $c);
                }
            },
            "order": [[ 7, "desc" ], [ 0, "asc" ]], 
            "columnDefs": [
                {
                    "targets": [ 0 ],
                    "visible": true,
                    "searchable": false
                }
            ], 
            "drawCallback": function( settings ) {
                var api = this.api();
                //wrap.loaded(settings);
                loaded(settings);
            }, 
            'initComplete': function(settings, json){
                //loaded(settings);
            },
            "language" : {
                "url": "/plugins/datatable_zhtw.json"
            }
        });
    }

The key is to add a listener to “xhr.dt” event before initialize datatable plugin.

Server side:

    protected function datatable_response($total, $filtered_total, $data=[], $draw=0){
        header('Content-Type: application/json');

        $out = array();
        $out['draw'] = $draw;
        $out['recordsTotal'] = $total;
        $out['recordsFiltered'] = $filtered_total;
        $out['data'] = $data;
        $out['message'] = 'test error';
     
        echo json_encode($out);
        exit();
    }

 

Reference:

  1. https://datatables.net/reference/event/xhr