1
 "ajax": {
            "url": url,
            "type": "GET",
            "datatype": "json",
            "data": { id: id}
            //,
            //"success": function (data) {
            //    if (!data.data)
            //        ShowErrorMessage(data.message);
            //}
        },
        "columns": [
                { "data": "ID" },
                { "data": "Name" },
                { "data": "Time" }
        ],
        "columnDefs": [{
            "targets": 2,
            "data": "Time",
            "render": function (data) {
                return (ToJavaScriptDate(data));
            }
        }]
    });

Above the sample code, which will populate a datatable using ajax GET call. The issue here is, sometimes I will return a valid error message instead of table data from ajax response.

So when ever there is data in data.data, I need to populate the table and if data is not there, I need to populate the data.message as custom error message. Here both the calls are success calls but whether to display the table content or error message depends.

I tried "success" attribute but I am not sure how to manually bind the columns when there is data in data.data

2
  • datatables.net/reference/option/language.emptyTable Commented Mar 20, 2017 at 10:26
  • @AlivetoDie I understand I can go for empty table message. The complexity here is I need to populate the message I got from ajax response as empty table message Commented Mar 20, 2017 at 10:28

1 Answer 1

2

The best way would be to use language.emptyTable option.

However since you want to use message from the Ajax response, there is a hacky way to do it.

var table = $('#example').DataTable({
    ajax: {
       url: 'https://api.myjson.com/bins/if7vf',
       dataSrc: function(d){
          if(d.data.length === 0){
             var settings = $('#example').DataTable().settings()[0];
             settings.oLanguage.sEmptyTable = d.message;
          }

          return d.data;
       }
    }
});

See this example for code and demonstration.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Please help to manipulate a particular column E.g. as mentioned in question ("Time") and few are hidden columns
@TechJerk, if you want to have 1 data row if no data is available, then instead of setting sEmptyTable variable you could do something like d.data.push({'ID': '', 'Name': '', 'Time': d.message}) to add 1 new row if there is no data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.