2

I'm new to DataTables, and I'm trying to handle the server-side errors on a JQuery DataTable allocated in an AngularJS directive. The idea is to display various informative and/or error messages inside the table. We are not allowed to use alerts, nor text outside the table.

So what I'm doing is:

VIEW

<div class="row">
    <div class="col-xs-12">
        <table id="tabla-recibos" class="table table-hover dataTable">
            <thead>
                <tr>
                    <!-- <th style="display:none;"><span data-translate="global.field.id">Id</th> -->
                    <th><span data-translate="webclientesApp.recibo.numRecibo">Núm. de póliza</th>
                    <th><span data-translate="webclientesApp.recibo.numPoliza">Expediente</th>
                    <th><span data-translate="webclientesApp.recibo.importe">Nombre del tomador</th>
                    <th><span data-translate="webclientesApp.recibo.fechaPago">Nombre del asegurado</th>
                    <th><span data-translate="webclientesApp.recibo.estado">Estado</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>
</div>

DIRECTIVE

$element.find('#tabla-recibos').DataTable({
                    autowidth: true,
                    pageLength: 5,
                    ajax: {
                        url: '/api/recibos/dni/' + $ctrl.dniUser,
                        type: "GET",
                        dataSrc: '',

                        success : function(data,textStatus,jqXHR) {
                            if (jqXHR.status == "204") {
                                $('#tabla-recibos').DataTable().clear().draw();         
                            }
                        },

                        error: function(jqXHR, exception){
                            $.fn.DataTable.ext.errMode = 'throw';
                            $('#tabla-recibos').DataTable().row().add("Not found");
                                }
                        },
                    columns: [
//                        { data: "id" },
                        { data: "numRecibo" },
                        { data: "numPoliza" },
                        { data: "importe" },
                        { data: "fechaPago" },
                        { data: "estado" }
                    ],
                    language: {
                        processing: "Tratamiento en curso...",
                        search: "Buscar&nbsp;:",
                        lengthMenu: "Mostrar _MENU_ elementos",
                        info: "Mostrando _START_ a _END_ de _TOTAL_ elementos",
                        infoEmpty: "Viendo los elementos 0 - 0 de _TOTAL_ elementos",
                        infoFiltered: "(filtrado de _TOTAL_ elementos)",
                        infoPostFix: "",
                        loadingRecords: "Cargando datos...",
                        zeroRecords: "No hay datos para mostrar",
                        emptyTable: "No existen recibos para este usuario",
                        paginate: {
                            first: "Primero",
                            previous: "Anterior",
                            next: "Siguiente",
                            last: "�ltimo"
                        },
                        aria: {
                            sortAscending: ": habilitado para ordenar la columna en orden ascendente",
                            sortDescending: ": habilitado para ordenar la columna en orden descendente"
                        }
                    },

As you can see, I'm trying to handle the error code 204 to clear the table, thus forcing the emptyTable text to appear. But when it comes to other error codes, such as 400, I want the text "Not found" to appear in the row, such as this:

enter image description here

So far, I've tried:

  • To add a row with DataTable().row().add()
  • Destroying the table, then reinitializing it
  • Editing the value of the current row

None of this have worked so far. Can you help me?

1 Answer 1

3

To quote the docs :

success - Must not be overridden as it is used internally in DataTables ...

Use error() to catch AJAX errors, basically to avoid nasty popups or console messages. Then use statusCode to perform different actions to different HTTP status codes. Here is an example :

var table = $('#example').DataTable({
  ajax: {
    url: 'url/to/server',
    //catch any errors so you not get nasty popups
    error: function(jqXHR, exception) {
    }, 
    statusCode: {
      200: function() { 
        console.log('OK 200') 
      },
      204: function() {
        console.log('Empty 204') 
        //language.emptyTable is shown automatically
      },
      400: function() {
        console.log('Bad Request 400');
        $('#example tbody')
          .empty()
          .append('<tr><td colspan="6" class="dataTables_empty">Bad request</td></tr>')
      },
      500: function() {
        console.log('Internal server error 500');
        $('#example tbody')
          .empty()
          .append('<tr><td colspan="6" class="dataTables_empty">Internal server error</td></tr>')
      }
    }
  },
  ...
})

Now change the messages to what you need. dataTables itself is injecting a

<tr>
  <td colspan="6" class="dataTables_empty">
    {{ language.emptyTable }}
  </td>
</tr>

So it is perfectly OK to do the same with an alternative message.

Note: You cannot prevent dataTables from showing language.emptyTable if the user somehow forces a redraw, like clicking on a header so sorting is triggered - this is just how it works. And you only have emptyTable and zeroRecords to deal with. But as You see, you can easily show different messages to different status codes, immediately after the AJAX call has finished or failed.

See a diminutive demo (cannot reproduce a 204) -> http://jsfiddle.net/qfwL3v11/

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

1 Comment

Spot on! I was trying pretty confusing and nasty things, I guess I can blame it on the inexperience... Thanks a lot David :)

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.