Search code examples
jqueryajaxerror-handlingdatatableserver-side

how to handle Ajax 401 (unauthorized access error) in Jquery datatables?


I am using a datatable as follows:

    $('#resources_table').dataTable({
    "processing": true,
    "serverSide": true,
    "columns": [
        { "data": "id" },
        { "data": "column1" },
        { "data": "column2" }
    ],
    "ajax": "/resource",
    "error": function(reason) {
        console.log("error encountered ! ");
        // process reason here to know the type of the error
        // and then take appropriate action
    }
});

Somehow I am not been able to catch error returned from the server. How to access reason and process error in serverside processing ajax based datatables?

PS: I am using the latest dataTable version: DataTables 1.10.1


Solution

  • Found it. Actually "ajax" takes one of the 3 types of values: either string or object or function.

    One can use an object to specify corresponding options for ajax request as shown in a simple example below:

    $('#resources_table').dataTable({
        "processing": true,
        "serverSide": true,
        "columns": [
            { "data": "id" },
            { "data": "column1" },
            { "data": "column2" }
        ],
        "ajax": {
            "type": "GET",
            "url" :"/resources",
            // error callback to handle error
            "error": function(xhr, error, thrown) {
                console.log("Error occurred!");
                console.log(xhr, error, thrown);
            }
        }
    });