I have a database table with a large amount of data, and it takes a lot of time to load into the datatable. So I use the server side script for load data for the current page only.
But now I need to add a new condition in 'where' section and when I add the condition, the search property of datatable not working.
I also need to sort the table by language_id it doesn't work at all
my code is
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Datatable with mysql</title>
<link rel="stylesheet" id="font-awesome-style-css" href="http://phpflow.com/code/css/bootstrap3.min.css" type="text/css" media="all">
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css"/>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
</head>
<body>
<div class="container">
<div class="">
<h1>Data Table</h1>
<div class="">
<table id="employee_grid" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>Empid</th>
<th>Name</th>
<th>Salary</th>
<th>Age</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Empid</th>
<th>Name</th>
<th>Salary</th>
<th>Age</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
<script type="text/javascript">
$( document ).ready(function() {
$('#employee_grid').DataTable({
"bProcessing": true,
"serverSide": true,
"ajax":{
url :"response.php", // json datasource
type: "post", // type of method ,GET/POST/DELETE
error: function(){
$("#employee_grid_processing").css("display","none");
}
}
});
});
</script>
</body>
</html>
response.php
<?php
//include connection file
include_once("connection.php");
// initilize all variable
$params = $columns = $totalRecords = $data = array();
$params = $_REQUEST;
//define index of column
$columns = array(
0 =>'blog_id',
1 =>'blog_caption',
2 => 'publisher_name',
3 => 'published_date'
);
$where = $sqlTot = $sqlRec = "";
// check search value exist
if( !empty($params['search']['value']) ) {
$where .=" WHERE ";
$where .=" ( blog_caption LIKE '".$params['search']['value']."%' ";
$where .=" OR publisher_name LIKE '".$params['search']['value']."%' ";
$where .=" OR published_date LIKE '".$params['search']['value']."%' )";
}
// getting total number records without any search
$sql = "SELECT blog_id,blog_caption,publisher_name,published_date FROM `blog_table` ";
$sqlTot .= $sql;
$sqlRec .= $sql;
//concatenate search sql if value exist
if(isset($where) && $where != '') {
$sqlTot .= $where;
$sqlRec .= $where;
}
$sqlRec .= " ORDER BY ". $columns[$params['order'][0]['column']]." ".$params['order'][0]['dir']." LIMIT ".$params['start']." ,".$params['length']." ";
$queryTot = mysqli_query($conn, $sqlTot) or die("database error:". mysqli_error($conn));
$totalRecords = mysqli_num_rows($queryTot);
$queryRecords = mysqli_query($conn, $sqlRec) or die("error to fetch employees data");
//iterate on results row and create new index array of data
while( $row = mysqli_fetch_row($queryRecords) ) {
$data[] = $row;
}
$json_data = array(
"draw" => intval( $params['draw'] ),
"recordsTotal" => intval( $totalRecords ),
"recordsFiltered" => intval($totalRecords),
"data" => $data // total data array
);
echo json_encode($json_data); // send data as json format
?>
Thanks in advance.
Related
Date picker for tabledit:
I have a php simple tabledit form with custom added insert button to create new entry that already work.
Because im not familiar with ajax that i want is simply to add a datepicker compatible with my tabledit
Data validation:
I think its critical to have validation,Not regex from client side i think most effective is from server side.
I made a simple "if" for validate the 'first_name' its working but i want also to do this for 'add' not only for 'edit' and able to export error if not valid.
Look please my example of code if you have an working idea for datepicker and also for a validation technique, i dont know what is better validation to make it with ajax with php? pealse give me an example for edit and for add procedure
index.php
<html>
<head>
<title>How to use Tabledit plugin with jQuery Datatable in PHP Ajax</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://markcell.github.io/jquery-tabledit/assets/js/tabledit.min.js"></script>
</head>
<body>
<div class="container">
<h3 align="center">How to use Tabledit plugin with jQuery Datatable in PHP Ajax</h3>
<br />
<div class="panel panel-default">
<button id="addRow">Add Row</button>
<div class="panel-body">
<div class="table-responsive">
<table id="sample_data" class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
</div>
<br />
<br />
</body>
</html>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
var dataTable = $('#sample_data').DataTable({
"processing": true,
"serverSide": true,
"order": [],
"ajax": {
url: "fetch.php",
type: "POST"
}
});
$('#sample_data').on('draw.dt', function() {
$('#sample_data').Tabledit({
url: 'action.php',
dataType: 'json',
columns: {
identifier: [0, 'id'],
editable: [
[1, 'first_name'],
[2, 'last_name'],
[3, 'gender', '{"1":"Male","2":"Female"}']
]
},
restoreButton: false,
onSuccess: function(data, textStatus, jqXHR) {
if (data.action == 'delete') {
$('#' + data.id).remove();
$('#sample_data').DataTable().ajax.reload();
}
}
});
});
//////////insert data///////////
$("#addRow").click(function() {
var tableditTableName = '#sample_data'; // Identifier of table
var newID = parseInt($(tableditTableName + " tr:last").attr("id")) + 1;
var clone = $("table tr:last").clone();
$(".tabledit-span", clone).text("");
$(".tabledit-input", clone).val("");
clone.prependTo("table");
$(tableditTableName + " tbody tr:first").attr("id", newID);
$(tableditTableName + " tbody tr:first td .tabledit-span.tabledit-identifier").text(newID);
$(tableditTableName + " tbody tr:first td .tabledit-input.tabledit-identifier").val(newID);
$(tableditTableName + " tbody tr:first td:last .tabledit-edit-button").trigger("click");
});
});
</script>
action.php
<?php
//action.php
include('database_connection.php');
if ($_POST['action'] == 'edit') {
/////////simple validation///////////
if (empty($_POST['first_name'])) {
$valid = false;
$errors['first_name'] = "name is required";
} else {
$data = array(
':first_name' => $_POST['first_name'],
':last_name' => $_POST['last_name'],
':sum' => $_POST['sum'],
':gender' => $_POST['gender'],
':id' => $_POST['id']
);
$query = "
UPDATE tbl_sample
SET first_name = :first_name,
last_name = :last_name,
sum = :sum,
gender = :gender
WHERE id = :id
";
$statement = $connect->prepare($query);
$statement->execute($data);
echo json_encode($_POST);
}
}
if ($_POST['action'] == 'delete') {
$query = "
DELETE FROM tbl_sample
WHERE id = '" . $_POST["id"] . "'
";
$statement = $connect->prepare($query);
$statement->execute();
echo json_encode($_POST);
}
fetch.php
<?php
//fetch.php
include('database_connection.php');
$column = array("id", "first_name", "last_name", "sum", "gender");
$query = "SELECT * FROM tbl_sample ";
if (isset($_POST["search"]["value"])) {
$query .= '
WHERE first_name LIKE "%' . $_POST["search"]["value"] . '%"
OR last_name LIKE "%' . $_POST["search"]["value"] . '%"
OR gender LIKE "%' . $_POST["search"]["value"] . '%"
';
}
if (isset($_POST["order"])) {
$query .= 'ORDER BY ' . $column[$_POST['order']['0']['column']] . ' ' . $_POST['order']['0']['dir'] . ' ';
} else {
$query .= 'ORDER BY id DESC ';
}
$query1 = '';
if ($_POST["length"] != -1) {
$query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connect->prepare($query);
$statement->execute();
$number_filter_row = $statement->rowCount();
$statement = $connect->prepare($query . $query1);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
foreach ($result as $row) {
$sub_array = array();
$sub_array[] = $row['id'];
$sub_array[] = $row['first_name'];
$sub_array[] = $row['last_name'];
$sub_array[] = $row['gender'];
$sub_array[] = $row['sum'];
$data[] = $sub_array;
}
function count_all_data($connect)
{
$query = "SELECT * FROM tbl_sample";
$statement = $connect->prepare($query);
$statement->execute();
return $statement->rowCount();
}
$output = array(
'draw' => intval($_POST['draw']),
'recordsTotal' => count_all_data($connect),
'recordsFiltered' => $number_filter_row,
'data' => $data
);
echo json_encode($output);
I have one table fetching data from database and displaying on page using PHP. i have created pagination using Ajax,PHP and MySQL. but when i am clicking on the page numbers, some time it is working and some time the table is displaying records on the first page irrespective of the page i clicked.please help me to solve this issue, i am trying since long time to resolve the issue and i could not. My main page is as follows.....
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Load Data without page refresh</title>
<!--<link rel="stylesheet" href="style/css/bootstrap.min.css">-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<!--<script src="scripts/js/bootstrap.min.js"></script>-->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<!--<script src="scripts/js/jquery.min.js"></script>-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<br /><br />
<div class="container">
<h3 align="center">Pagintation without page refresh</h3>
<div class="table-responsive" id="pagination_data">
</div>
</div>
</body>
</html>
<script>
$(document).ready(function() {
load_data();
function load_data(page) {
$.ajax({
url: "pagination.php",
method: "POST",
data: {
page: page
},
success: function(data) {
$('#pagination_data').html(data);
}
})
}
$(document).on('click', '.pagination_link', function() {
var page = $(this).attr("id");
//alert(page);
load_data(page);
});
});
</script>
pagination.php
<?php
//pagination.php
$connect = mysqli_connect("localhost", "root", "", "testing");
$record_per_page = 5;
$page = '';
$output = '';
if(isset($_POST["page"]))
{
$page = $_POST["page"];
}
else
{
$page = 1;
}
$start_from = ($page - 1)*$record_per_page;
$query = "SELECT * FROM tbl_student ORDER BY student_id DESC LIMIT $start_from, $record_per_page";
$result = mysqli_query($connect, $query);
$output .= "
<table class='table table-bordered'>
<tr>
<th width='50%'>Name</th>
<th width='50%'>Phone</th>
</tr>
";
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["student_name"].'</td>
<td>'.$row["student_phone"].'</td>
</tr>
';
}
$output .= '</table><br /><div align="center">';
$page_query = "SELECT * FROM tbl_student ORDER BY student_id DESC";
$page_result = mysqli_query($connect, $page_query);
$total_records = mysqli_num_rows($page_result);
$total_pages = ceil($total_records/$record_per_page);
for($i=1; $i<=$total_pages; $i++)
{
$output .= "<span class='pagination_link' style='cursor:pointer; padding:6px; border:1px solid #ccc;' id='".$i."'>".$i."</span>";
}
$output .= '</div><br /><br />';
echo $output;
?>
what happen in the code is that everytime i choose in multiple drop down it fetch the data what i want to happen is to click the button first then it will fetch the data...... thank u guys got the code in here https://www.webslesson.info/2018/05/ajax-live-data-search-using-multi-select-dropdown-in-php.html
<?php
//index.php
$connect = new PDO("mysql:host=localhost;dbname=db", "root", "");
$query = "SELECT DISTINCT Country FROM tbl_customer ORDER BY Country ASC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax Live Data Search using Multi Select Dropdown in PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<link href="css/bootstrap-select.min.css" rel="stylesheet" />
<script src="js/bootstrap-select.min.js"></script>
</head>
<body>
<div class="container">
<br />
<h2 align="center">Ajax Live Data Search using Multi Select Dropdown in PHP</h2><br />
<select name="multi_search_filter" id="multi_search_filter" multiple class="form-control selectpicker">
<?php
foreach($result as $row)
{
echo '<option value="'.$row["Country"].'">'.$row["Country"].'</option>';
}
?>
</select>
<input type="hidden" name="hidden_country" id="hidden_country" />
<div style="clear:both"></div>
<br />
<div class="table-responsive">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Customer Name</th>
<th>Address</th>
<th>City</th>
<th>Postal Code</th>
<th>Country</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<br />
<br />
<br />
</div>
</body>
</html>
<script>
$(document).ready(function(){
load_data();
function load_data(query='')
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('tbody').html(data);
}
})
}
$('#multi_search_filter').change(function(){
$('#hidden_country').val($('#multi_search_filter').val());
var query = $('#hidden_country').val();
load_data(query);
});
});
</script>
fetch.php
//fetch.php
$connect = new PDO("mysql:host=localhost;dbname=dbattendancelibrary", "root", "");
if($_POST["query"] != '')
{
$search_array = explode(",", $_POST["query"]);
$search_text = "'" . implode("', '", $search_array) . "'";
$query = "
SELECT * FROM tbl_customer
WHERE Country IN (".$search_text.")
ORDER BY CustomerID DESC
";
}
else
{
$query = "SELECT * FROM tbl_customer ORDER BY CustomerID DESC";
}
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$total_row = $statement->rowCount();
$output = '';
if($total_row > 0)
{
foreach($result as $row)
{
$output .= '
<tr>
<td>'.$row["CustomerName"].'</td>
<td>'.$row["Address"].'</td>
<td>'.$row["City"].'</td>
<td>'.$row["PostalCode"].'</td>
<td>'.$row["Country"].'</td>
</tr>
';
}
}
else
{
$output .= '
<tr>
<td colspan="5" align="center">No Data Found</td>
</tr>
';
}
echo $output;
?>
It fires an ajax call because of this code:
$('#multi_search_filter').change(function(){
$('#hidden_country').val($('#multi_search_filter').val());
var query = $('#hidden_country').val();
load_data(query);
});
If you want to fire when clicking on a button, you will need to put in HTML for the button first. Then use the id for load_data event, for example you will have a button called '#btn_search':
$('#multi_search_filter').change(function(){
$('#hidden_country').val($('#multi_search_filter').val());
});
$('#btn_search').click(function(e){
e.preventDefault();
var query = $('#hidden_country').val();
load_data(query);
});
Your full HTML above becomes like this:
<?php
//index.php
$connect = new PDO("mysql:host=localhost;dbname=db", "root", "");
$query = "SELECT DISTINCT Country FROM tbl_customer ORDER BY Country ASC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax Live Data Search using Multi Select Dropdown in PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<link href="css/bootstrap-select.min.css" rel="stylesheet" />
<script src="js/bootstrap-select.min.js"></script>
</head>
<body>
<div class="container">
<br />
<h2 align="center">Ajax Live Data Search using Multi Select Dropdown in PHP</h2><br />
<select name="multi_search_filter" id="multi_search_filter" multiple class="form-control selectpicker">
<?php
foreach($result as $row)
{
echo '<option value="'.$row["Country"].'">'.$row["Country"].'</option>';
}
?>
</select>
<input id="btn_search" type="button" value="Filter" />
<input type="hidden" name="hidden_country" id="hidden_country" />
<div style="clear:both"></div>
<br />
<div class="table-responsive">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Customer Name</th>
<th>Address</th>
<th>City</th>
<th>Postal Code</th>
<th>Country</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<br />
<br />
<br />
</div>
</body>
</html>
<script>
$(document).ready(function(){
load_data();
function load_data(query='')
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('tbody').html(data);
}
})
}
$('#multi_search_filter').change(function(){
$('#hidden_country').val($('#multi_search_filter').val());
});
$('#btn_search').click(function(e){
e.preventDefault();
var query = $('#hidden_country').val();
load_data(query);
});
});
</script>
How do I display all the records from a query that I executed into a table when I choose a id from my car_types drop-down-menu.
Here is the code I had done so far, I keep getting an error whenever I run my SQL query
$carResult = mysqli_query($link, $carQuery), how do I solve it or is my method of doing wrong?
Error: Warning: mysqli_error() expects exactly 1 parameter, 0 given in C:\xampp\htdocs\Cars\carShop.php on line 54
index.php
<?php
$link = mysqli_connect('localhost', 'root', '', 'db_car');
if (!$link) {
die(mysqli_error($link));
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Car Shop</title>
<script type="text/javascript" src="script/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#type").change(function() {
$.ajax({
type: "GET",
url: "getCars.php",
data: "type_id=" + $(this).find(":selected").val(),
cache: false,
success: function(msg){
query = $.parseJSON(msg);
$('#query').html(query);
}
});
});
$("#type").trigger('change');
});
</script>
</head>
<body>
<select id="type" name="type">
<?php
$query = "SELECT * FROM car_types";
$result = mysqli_query($link, $query) or die(mysqli_error());
while ($row = mysqli_fetch_assoc($result)) {
echo "<option value ='" . $row['id'] . "'>" . $row['type_name'] . "</option>";
}
?>
</select><br>
<table border="1">
<tr>
<th>Car ID</th>
<th>Name</th>
<th>Price</th>
</tr>
<?php
$carQuery = " <div id='query'></div>";
echo $carQuery;
$carResult = mysqli_query($link, $carQuery) or die(mysqli_error());
while($row = mysqli_fetch_assoc($carResult)) { ?>
<tr>
<td><?php echo $row['id'];?><td>
<td><?php echo $row['name'];?><td>
<td><?php echo $row['price'];?><td>
</tr>
<?php } ?>
</table>
</body>
</html>
getCars.php
<?php
$link = mysqli_connect('localhost', 'root', '', 'db_car');
if (!$link) {
die(mysqli_error($link));
}
$typeId = $_GET['type_id'];
$query = "SELECT * FROM cars WHERE type_id = $typeId";
echo json_encode($query);
?>
You are trying to execute a query
$carQuery = " <div id='query'></div>";
echo $carQuery;
$carResult = mysqli_query($link, $carQuery) or die(mysqli_error());
While $carQuery is a div with a query in it, that's not gonna work. Try to execute this query within getCars.php and return the result.
Something like this:
<?php
$link = mysqli_connect('localhost', 'root', '', 'db_car');
if (!$link) {
die(mysqli_error($link));
}
$typeId = $_GET['type_id'];
$query = "SELECT * FROM cars WHERE type_id = $typeId";
$carResult = mysqli_query($link, $query) or die(mysqli_error());
while($row = mysqli_fetch_assoc($carResult)) {
echo "<tr>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['id']."</td>";
echo "</tr>";
}
?>
All you have to do now is assign the results to the right table via the success function of your AJAX call.
In your index.php
<?php
$link = mysqli_connect('localhost', 'root', '', 'db_car');
if (!$link) {
die(mysqli_error($link));
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Car Shop</title>
<script type="text/javascript" src="script/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#type").change(function() {
$.ajax({
type: "GET",
url: "getCars.php",
data: "type_id=" + $(this).find(":selected").val(),
cache: false,
success: function(rslt){
$('#carResult').html(rslt);
}
});
});
$("#type").trigger('change');
});
</script>
</head>
<body>
<select id="type" name="type">
<?php
$query = "SELECT * FROM car_types";
$result = mysqli_query($link, $query) or die(mysqli_error());
while ($row = mysqli_fetch_assoc($result)) {
echo "<option value ='" . $row['id'] . "'>" . $row['type_name'] . "</option>";
}
?>
</select><br>
<table border="1">
<thead>
<tr>
<th>Car ID</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody id="carResult">
</tbody>
</table>
</body>
I'm just having some trouble initializing a DataTable using Ajax and PHP. According to the inspector the error is:
Uncaught TypeError: Cannot read property 'length' of undefined jquery.dataTables.js:2649
(anonymous function) jquery.dataTables.js:2649
oSettings.jqXHR.$.ajax.success jquery.dataTables.js:8749
c jquery.js:3048
p.fireWith jquery.js:3160
k jquery.js:8235
r jquery.js:8778
I've followed the instructions as on datatable website but apparently I'm doing something wrong. It's not the php part, I've just checked it and it is returning a json file.
Here's what I've got.
Thanks in advance.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Chromo Insiders</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="DataTables/media/js/jquery.dataTables.js"></script>
<script type="application/javascript" language="javascript" src="insiders.js"></script>
<link rel="stylesheet" type="text/css" href="ci_style.css" />
<style type="text/css">
#import 'DataTables/media/css/demo_table_jui.css';
</style>
</head>
<body>
<header>
<h1>Chromo Insiders</h1>
</header>
<table id="datatables">
<thead>
<tr>
<th>email</th>
<th>Last Name</th>
<th>First Name</th>
<th>Date Registered</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
Here's the script:
$(document).ready(function(e) {
$('#datatables').dataTable( {
"bProcessing": true,
"sAjaxSource": 'process.php'
} );
});
Just in case you need to take a look to the php code:
<?php
try {
$conn = require_once 'dbConnect.php';
$sql = "SELECT email, lastName, firstName, state, dateRegistered FROM Users";
$result = $conn->prepare($sql) or die ($sql);
if(!$result->execute()) return false;
if($result->rowCount() > 0) {
$json = array();
while($row = $result->fetch()){
$json[] = array(
'email' => $row['email'],
'lastName' => $row['lastName'],
'firstName' => $row['firstName'],
'dateRegistered' => $row['dateRegistered'],
'state' => $row['state']
);
}
$json['success'] = true;
echo json_encode($json);
}
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
?>
You need to change your response as such:
if($result->rowCount() > 0) {
$json = array();
while($row = $result->fetch()){
/** MAKE ARRAY NON ASSOCIATIVE **/
$json[] = array(
$row['email'],
$row['lastName'],
$row['firstName'],
$row['dateRegistered'],
$row['state']
);
}
/*** MAKE RESPONSE HAVE 'aaData' ENTRY ****/
$response = array();
$response['success'] = true;
$response['aaData'] = $json;
echo json_encode($response);
Reference here: http://datatables.net/release-datatables/examples/data_sources/ajax.html. Specifically:
DataTables expects an object with an array called "aaData" with the
data source.
Also your table does not have a 'state' column, although your ajax response does...