Link to home
Start Free TrialLog in
Avatar of Opeyemi AbdulRasheed
Opeyemi AbdulRasheed

asked on

AJAX Response When Query Returns Empty Data

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.
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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

Avatar of Opeyemi AbdulRasheed
Opeyemi AbdulRasheed

ASKER

@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