Jquery – Throw ajax error incase of custom exception using JSON object while populating datatable using datatables jquery plugin

jqueryjquery-datatablesjson

I am new to MVC and Jquery. I am currently using datatables plugin from jquery to populate a table in my application. My issue is when the application loads for the first time, sAjaxSource is used to specify the url where data is loaded from(JSON Object is returned).

My issue is I have few custom exceptions to catch while loading the data. But I am not sure how to pass this as an error using JSON and where do we catch error on client side. I did not find any option which specifies success or error result of ajax call while the datatable populates. My reference link is http://www.datatables.net/ref#sDom

Best Answer

It seems you need to use the fnServerData callback. I have never used it myself, but it seems you can manually do the ajax request and catch any server-side errors you want.

In your case it would be something like this:

$(document).ready( function() {
    try {
        $('#example').dataTable( {
        "bProcessing": true,
        "bServerSide": true,
        "sAjaxSource": "xhr.php",
        "fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
          oSettings.jqXHR = $.ajax( {

            "dataType": 'json', 

            "type": "POST", 

            "url": sSource, 

            "data": aoData, 

            "success": function(response) {
                 //do error checking here, maybe "throw new Error('Some error')" based on data;
                 fnCallback(arguments);
            },

            "error": function() { //404 errors and the like wil fall here
                //"throw new Error('Some error')"
            }
          } );
        }
        } );
    } catch (e) {
        console.error(e);
    }
} );

Again I never used that callback before, but from the reference it seems to be the right way to do it.

Well that is the part on how to catch the error on the client side. As for what to send when there is an error it varies based on your language and framework. If your project is non-trivial and you do a lot of ajax requests like that I recommend you building a REST API for getting your data.

Or you can just catch your errors on the server side and return a json like this:

{
   returnStatus: "error",
   message: "message"
}

and when the request is succesful just return something like this:

{
   returnStatus: "success",
   data: [...]
}

And just check for returnStatus on the ajax "success" callback.

Related Topic