1

I’m trying to build a CRUD application. I have a MySQL database of a large amount of records and would like to use a JQuery DataTable rather than trying to code out a table from scratch. The problem I have, is that I can see the table on my site, but I cannot get it to pull in the data from MySQL.

I’ve tried reading many site and forums including the official documentation on DataTable’s website, but none of it makes sense to me.

What do I need to do to fix this? I’ve been working on this project for a solid week and am getting frustrated.

<?php

/*
 * DataTables example server-side processing script.
 *
 * Please note that this script is intentionally extremely simple to show how
 * server-side processing can be implemented, and probably shouldn't be used as
 * the basis for a large complex system. It is suitable for simple use cases as
 * for learning.
 *
 * See http://datatables.net/usage/server-side for full details on the server-
 * side processing requirements of DataTables.
 *
 * @license MIT - http://datatables.net/license_mit
 */

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Easy set variables
 */

// DB table to use
$table = 'members';

// Table's primary key
$primaryKey = 'id';

// Array of database columns which should be read and sent back to DataTables.
// The `db` parameter represents the column name in the database, while the `dt`
// parameter represents the DataTables column identifier. In this case simple
// indexes
$columns = array(
    array( 'db' => 'id', 'dt' => 0 ),
    array( 'db' => 'name',  'dt' => 1 ),
    array( 'db' => 'residential_address', 'dt' => 2 ),
    array( 'db' => 'mailing_address', 'dt' => 3 ),
    array( 'db' => 'precinct', 'dt' => 4)
    array( 'db' => 'age', 'dt' => 5 ),
    array( 'db' => 'ethnicity',  'dt' => 6 ),
    array( 'db' => 'gender', 'dt' => 7 ),
    array( 'db' => 'party', 'dt' => 8 ),
    array( 'db' => 'race', 'dt' => 9 ),
    array( 'db' => 'phone', 'dt' => 10 )        
);

// SQL server connection information
$sql_details = array(
    'user' => 'root',
    'pass' => '',
    'db'   => 'ccrp_db',
    'host' => 'localhost'
);


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * If you just want to use the basic configuration for DataTables with PHP
 * server-side, there is no need to edit below this line.
 */

require( 'ssp.class.php' );

echo json_encode(
    SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
);
?>

1]

Below is also my HTML code for reference:

<!DOCTYPE html>
<html lang="en">

<head>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">

  <title>Cabarrus County Republican Party | Member Database</title>

  <!-- Custom fonts for this template -->
  <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">

  <!-- Custom styles for this template -->
  <link href="css/sb-admin-2.min.css" rel="stylesheet">

  <!-- Custom styles for this page -->
  <link href="vendor/datatables/dataTables.bootstrap4.min.css" rel="stylesheet">

</head>

<body id="page-top">

  <!-- Page Wrapper -->
  <div id="wrapper">

    <!-- Sidebar -->
    <ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar">

      <!-- Sidebar - Brand -->
      <a class="sidebar-brand d-flex align-items-center justify-content-center" href="index.html">
        <!--<div class="sidebar-brand-icon rotate-n-15">
          <i class="fas fa-laugh-wink"></i>
        </div> -->
        <div class="sidebar-brand-text mx-3"><img src="img/republican_logo.png" width = "50" height="50">&nbsp;&nbsp;CCRP</div>
      </a>

      <!-- Divider -->
      <hr class="sidebar-divider my-0">

      <!-- Nav Item - Dashboard -->
      <li class="nav-item active">
        <a class="nav-link" href="index.html">
          <i class="fas fa-fw fa-table"></i>
          <span>Database</span></a>
      </li>

      <!-- Divider -->
      <hr class="sidebar-divider">

      <!-- Heading -->
      <div class="sidebar-heading">
        User Interface
      </div>

      <!-- Nav Item - Pages Collapse Menu -->
      <li class="nav-item">
        <a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapsePages" aria-expanded="true" aria-controls="collapsePages">
          <i class="fas fa-fw fa-tachometer-alt"></i>
          <span>Menu</span>
        </a>
        <div id="collapsePages" class="collapse" aria-labelledby="headingPages" data-parent="#accordionSidebar">
          <div class="bg-white py-2 collapse-inner rounded">
            <h6 class="collapse-header">Update Database</h6>
            <a class="collapse-item" href="create.html">Add New Members</a>
            <a class="collapse-item" href="#">Email <small>(beta)</small></a>
            <a class="collapse-item" href="#">Mass Email <small>(beta)</small></a>          
            <h6 class="collapse-header">User Account</h6>
            <a class="collapse-item" href="login.html">Login</a>
            <a class="collapse-item" href="register.html">Register</a>
            <a class="collapse-item" href="forgot-password.html">Forgot Password</a>
            <div class="collapse-divider"></div>
            <!-- <a class="collapse-item" href="blank.html">Blank Page</a> -->
          </div>
        </div>
      </li>

      <!-- Divider -->
      <hr class="sidebar-divider d-none d-md-block">

      <!-- Sidebar Toggler (Sidebar) -->
      <div class="text-center d-none d-md-inline">
        <button class="rounded-circle border-0" id="sidebarToggle"></button>
      </div>

    </ul>
    <!-- End of Sidebar -->

    <!-- Content Wrapper -->
    <div id="content-wrapper" class="d-flex flex-column">

      <!-- Main Content -->
      <div id="content">

        <!-- Topbar -->
        <nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow">

          <!-- Sidebar Toggle (Topbar) -->
          <button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3">
            <i class="fa fa-bars"></i>
          </button>

          <!-- Topbar Search -->
          <form class="d-none d-sm-inline-block form-inline mr-auto ml-md-3 my-2 my-md-0 mw-100 navbar-search">
            <div class="input-group">
              <input type="text" class="form-control bg-light border-0 small" placeholder="Search for..." aria-label="Search" aria-describedby="basic-addon2">
              <div class="input-group-append">
                <button class="btn btn-primary" type="button">
                  <i class="fas fa-search fa-sm"></i>
                </button>
              </div>
            </div>
          </form>

          <!-- Topbar Navbar -->
          <ul class="navbar-nav ml-auto">

            <!-- Nav Item - Search Dropdown (Visible Only XS) -->
            <li class="nav-item dropdown no-arrow d-sm-none">
              <a class="nav-link dropdown-toggle" href="#" id="searchDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                <i class="fas fa-search fa-fw"></i>
              </a>
              <!-- Dropdown - Messages -->
              <div class="dropdown-menu dropdown-menu-right p-3 shadow animated--grow-in" aria-labelledby="searchDropdown">
                <form class="form-inline mr-auto w-100 navbar-search">
                  <div class="input-group">
                    <input type="text" class="form-control bg-light border-0 small" placeholder="Search for..." aria-label="Search" aria-describedby="basic-addon2">
                    <div class="input-group-append">
                      <button class="btn btn-primary" type="button">
                        <i class="fas fa-search fa-sm"></i>
                      </button>
                    </div>
                  </div>
                </form>
              </div>
            </li>

            <!-- <div class="topbar-divider d-none d-sm-block"></div> -->

            <!-- Nav Item - User Information -->
            <li class="nav-item dropdown no-arrow">
              <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                <span class="mr-2 d-none d-lg-inline text-gray-600 small">Valerie Luna</span>
                <img class="img-profile rounded-circle" src="https://source.unsplash.com/QAB-WJcbgJk/60x60">
              </a>
              <!-- Dropdown - User Information -->
              <div class="dropdown-menu dropdown-menu-right shadow animated--grow-in" aria-labelledby="userDropdown">
                <a class="dropdown-item" href="#">
                  <i class="fas fa-user fa-sm fa-fw mr-2 text-gray-400"></i>
                  Profile
                </a>
                <a class="dropdown-item" href="#">
                  <i class="fas fa-cogs fa-sm fa-fw mr-2 text-gray-400"></i>
                  Settings
                </a>
                <a class="dropdown-item" href="#">
                  <i class="fas fa-list fa-sm fa-fw mr-2 text-gray-400"></i>
                  Activity Log
                </a>
                <div class="dropdown-divider"></div>
                <a class="dropdown-item" href="#" data-toggle="modal" data-target="#logoutModal">
                  <i class="fas fa-sign-out-alt fa-sm fa-fw mr-2 text-gray-400"></i>
                  Logout
                </a>
              </div>
            </li>

          </ul>

        </nav>
        <!-- End of Topbar -->

        <!-- Begin Page Content -->
        <div class="container-fluid">

          <!-- Page Heading -->
          <h1 class="h3 mb-2 text-gray-800">Members List</h1>
          <!-- <p class="mb-4">DataTables is a third party plugin that is used to generate the demo table below. For more information about DataTables, please visit the <a target="_blank" href="https://datatables.net">official DataTables documentation</a>.</p> -->

          <!-- DataTales Example -->
          <div class="card shadow mb-4">
            <div class="card-header py-3">
              <h6 class="m-0 font-weight-bold text-primary">Cabarrus County Republican Party </h6>
            </div>
            <div class="card-body">
              <div class="table-responsive">
                <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
                  <thead>
                    <tr>
                      <th>ID</th>
                      <th>Name</th>
                      <th>Residential Address</th>
                      <th>Mailing Address</th>
                      <th>Precinct</th>
                      <th>Age</th>
                      <th>Ethnicity</th>
                      <th>Gender</th>
                      <th>Party</th>
                      <th>Race</th>
                      <th>Phone Number</th>
                    </tr>
                  </thead>
                  <tfoot>
                    <tr>
                      <th>ID</th>
                      <th>Name</th>
                      <th>Residential Address</th>
                      <th>Mailing Address</th>
                      <th>Precinct</th>
                      <th>Age</th>
                      <th>Ethnicity</th>
                      <th>Gender</th>
                      <th>Party</th>
                      <th>Race</th>
                      <th>Phone Number</th>
                    </tr>
                  </tfoot>
                </table>
              </div>
            </div>
          </div>

        </div>
        <!-- /.container-fluid -->

      </div>
      <!-- End of Main Content -->

      <!-- Footer -->
      <footer class="sticky-footer bg-white">
        <div class="container my-auto">
          <div class="copyright text-center my-auto">
            <span>Copyright &copy; <a href="https://cascosigns.com">Casco Signs Inc.</a> 2019</span>
          </div>
        </div>
      </footer>
      <!-- End of Footer -->

    </div>
    <!-- End of Content Wrapper -->

  </div>
  <!-- End of Page Wrapper -->

  <!-- Scroll to Top Button-->
  <a class="scroll-to-top rounded" href="#page-top">
    <i class="fas fa-angle-up"></i>
  </a>

  <!-- Logout Modal-->
  <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5>
          <button class="close" type="button" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">×</span>
          </button>
        </div>
        <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>
        <div class="modal-footer">
          <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
          <a class="btn btn-primary" href="login.html">Logout</a>
        </div>
      </div>
    </div>
  </div>

  <!-- Bootstrap core JavaScript-->
  <script src="vendor/jquery/jquery.min.js"></script>
  <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

  <!-- Core plugin JavaScript-->
  <script src="vendor/jquery-easing/jquery.easing.min.js"></script>

  <!-- Custom scripts for all pages-->
  <script src="js/sb-admin-2.min.js"></script>

  <!-- Page level plugins -->
  <script src="vendor/datatables/jquery.dataTables.min.js"></script>
  <script src="vendor/datatables/dataTables.bootstrap4.min.js"></script>

  <!-- Page level custom scripts -->
  <script src="js/datatables.js"></script>

</body>

</html>

Jeremy Myrtle
  • 97
  • 2
  • 13

2 Answers2

1

Now that you've got your MySQL data into JSON using PHP, use DataTable's AJAX option to make it reflect your table:

$(document).ready(function() {
    $('#example').DataTable( {
        "processing": true,
        "serverSide": true,
        "ajax": "../server_side/scripts/server_processing.php" // your php file
    });
});
chakeda
  • 1,551
  • 1
  • 18
  • 40
  • I still don't see it. I actually changed my PHP file to the one mentioned in DataTable's manual and it isn't working still. I updated the code above. – Jeremy Myrtle Nov 08 '19 at 20:36
  • I don't see any. How can I check this? – Jeremy Myrtle Nov 08 '19 at 20:42
  • Access your PHP file directly to see any PHP errors. Open your browser's development tools and check the console for errors too. – chakeda Nov 08 '19 at 20:43
  • Had a syntax error and resolved it. So now, the PHP file is pulling in the data, but the table on the site still doesn't show? – Jeremy Myrtle Nov 08 '19 at 20:45
  • We're getting there! Anything in your browser's developer tools? – chakeda Nov 08 '19 at 20:46
  • Not that I can see. I'm using Chrome for this if that helps... where will Chrome shows errors if any are present? – Jeremy Myrtle Nov 08 '19 at 20:47
  • Chome will give you noticeable errors. Have you replaced your existing `$('#myTable')` selector with the right ID? Also, I don't know how your data looks like, but refer to the DataTable examples to get the right formatting: https://datatables.net/examples/ajax/ – chakeda Nov 08 '19 at 20:56
  • Here is one of my records: `{"draw":0,"recordsTotal":46893,"recordsFiltered":46893,"data":[["1","ABERCROMBIE, NOAH THOMAS","16111 BLACKBERRY HILLS DR MIDLAND, NC 28107","16111 BLACKBERRY HILLS DR MIDLAND, NC 28107","01-02","28","NL","M","REP","W",null],` And yes, I replaced the table name as you suggested. Still nothing. – Jeremy Myrtle Nov 08 '19 at 20:59
  • Ah I see now you're using the Server side script example. (https://datatables.net/examples/data_sources/server_side.html) See my updated answer. – chakeda Nov 08 '19 at 21:01
  • Correct. All of my data is coming from a MySQL database. I replaced the code with your updated answer and updated the necessary parameters. Still nothing. It only shows "No data available in this table." – Jeremy Myrtle Nov 08 '19 at 21:07
  • Hmm. Is your HTML and JavaScript any different from the manual? Try posting your code. – chakeda Nov 08 '19 at 21:15
  • I've added my HTML. Not sure what is needed from javascript. The only JS I have is the file that calls in the DataTable which you posted. – Jeremy Myrtle Nov 08 '19 at 21:18
  • HTML looks fine. Is the AJAX call getting any data? In Chrome developer tools, if you go to the network tab, see if you successfully hit the PHP file you created. – chakeda Nov 08 '19 at 21:21
  • It doesn't appear in the list when I reload the page. – Jeremy Myrtle Nov 08 '19 at 21:22
  • I got in touch with DataTables and they said that my draw value looks wrong. What does this mean? – Jeremy Myrtle Nov 11 '19 at 21:49
  • From what I see, the `draw` value should be '1', indicating that the table has been drawn - yours is '0'. This seems to stem from the fact that your AJAX request isn't hitting your PHP file. – chakeda Nov 11 '19 at 22:13
  • I'm not sure how to fix the draw value. So, perhaps it has something to do with my php file? – Jeremy Myrtle Nov 12 '19 at 13:46
  • I was able to resolve this in a different forum. Thank you. – Jeremy Myrtle Nov 13 '19 at 15:40
0

Though I see that it is fixed, I share this so that others reading this topic can get help.

Here is one of the solutions:

After getting json response, you can populate datatable by following the practice based on this jsfiddle link:

http://jsfiddle.net/gh/get/jquery/2.2/chennighan/RapidlyPrototypeJavaScript/tree/master/lesson4/

$(function() {
  $("#example").DataTable();

  // Premade test data, you can also use your own
  var testDataUrl = "https://raw.githubusercontent.com/chennighan/RapidlyPrototypeJavaScript/master/lesson4/data.json"

  $("#loadData").click(function() {
    loadData();
  });

  function loadData() {
    $.ajax({
      type: 'GET',
      url: testDataUrl,
      contentType: "text/plain",
      dataType: 'json',
      success: function (data) {
        myJsonData = data;
        populateDataTable(myJsonData);
      },
      error: function (e) {
        console.log("There was an error with your request...");
        console.log("error: " + JSON.stringify(e));
      }
    });
  }

  // populate the data table with JSON data
  function populateDataTable(data) {
    console.log("populating data table...");
    // clear the table before populating it with more data
    $("#example").DataTable().clear();
    var length = Object.keys(data.customers).length;
    for(var i = 1; i < length+1; i++) {
      var customer = data.customers['customer'+i];

      // You could also use an ajax property on the data table initialization
      $('#example').dataTable().fnAddData( [
        customer.first_name,
        customer.last_name,
        customer.occupation,
        customer.email_address
      ]);
    }
  }
})();
serhat
  • 11
  • 4