AJAX Response When Query Returns Empty Data

Opeyemi AbdulRasheed
Opeyemi AbdulRasheed used Ask the Experts™
on
Hello Experts!

I normally populate DataTable with the following combination. When a button is clicked, the table is populated through AJAX call as long as there's at least 1 row of data. But if there're no data in the table from MySQL, nothing happens. So, I want a message to return when there's no data coming from database.

Please help me manipulate this:

<?php 

require_once '../.../db_connection.php';

$stmt = $conn->prepare( "SELECT ... FROM ... WHERE ..." );
$stmt->bind_param( "ssssi", $_POST['session'], $_POST['term'], $_POST['class'], $_POST['subject'], $_POST['limit'] );
$stmt->execute();

$assessment = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
die( json_encode($assessment) );
?>

Open in new window



Here is my AJAX:
$('#loadStudents').click(function() {
   $.ajax({
   method : 'post',
   url : '../data/ass1_Data',
   data : { session : $('#session').val(), term : $('#term').val(), class : $('#c_taught').val(), subject : $('#s_taught').val(), limit : $('#process_limit').val(), },
   dataType : 'json',
   }).done(function(data) {
      myDt.clear().draw();
      myDt.rows.add(data).draw();
   });
});

Open in new window


Thank you in advance.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2017
Distinguished Expert 2018
Commented:
in your callback

.done(function(data) {
  If (data.length) {
    // there were records so process them
    myDt.clear().draw();
    myDt.rows.add(data).draw();
  }
  else {
    // do your "no records found here"
  }
});

Open in new window

Zakaria AcharkiAnalyst Developer
Distinguished Expert 2018

Commented:
Try to add the emptyTable option to the definition of your datatable object :

var myDt = $('#my-datatable').DataTable( {
    "language": {
        "emptyTable":     "There no row message."
    }
} );

Open in new window

@Julian Hansen, thank you sir, but there's syntax error. The IF under .done(function(data) { shows a wrong color code in my Sublime Text, which means syntax error. Kindly check, sir.

@Zakaria Acharki, thank you for your help, sir. There's already a "No data available in table" as built-in message for emptyTable. I just want an action response after clicking on Load Button.
@@Julian Hansen, forgive me sir. I copied pasted your code (CAPITAL If). Lazy me. I figured it out after sending the previous comment. It's working perfectly, sir.
Thanks both

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial