Oualid
Oualid

Reputation: 403

Datatables callback/event when empty ajax response

The code below does the following things:

  1. Sends a request to getData.php to get some data.
  2. The spinner is shown when the server-side code is working to retrieve data.
  3. The spinner is hidden when the data has come

My problem is that I don't know how to do to hide the spinner even when no data is coming.

The jquery code:

<script type="text/javascript">

$(document).ready(function() {

    var spinnerOpts = {
      // Options for the spinner here...
      ...   
   };

   var target = document.getElementById('spinn');
   var spinner = new Spinner(spinnerOpts);


    $('#myTable').dataTable( {
       "bProcessing": true,
       "sAjaxSource": "getData.php",
       "fnPreDrawCallback": function() {                    
         spinner.spin(target);    // Show the spinner
       },
       "fnRowCallback": function() {                        
       spinner.stop();   // Hide the spinner
      }

    } );
} );                

</script>

The following code sends a json string from getData.php when there is no data:

echo '{
    "sEcho": 1,
    "iTotalRecords": "0",
    "iTotalDisplayRecords": "0",
    "aaData": []
}';     

Upvotes: 0

Views: 2427

Answers (2)

Oualid
Oualid

Reputation: 403

I found the solution:

fnDrawCallback: function () {
  var rows = this.fnGetData();
  if ( rows.length === 0 ) {
     spinner.stop();
  }
},

Upvotes: 2

Alex Tape
Alex Tape

Reputation: 2291

you tried to inspect the element

   "fnRowCallback": function( e ) {                        
   console.log(e);   // maybe there is a state of the response in it ;) ?
   spinner.stop();   // Hide the spinner
  }

no time for testing it properly..

Upvotes: 0

Related Questions