Here I am new to ajax DataTables. I am trying to connect my database and fetch records to the dataTable. But I got this error:
datatables warning table id=datatables-example - invalid json
responseFor more information about this error, please see
http://datatables.net/tn/1
I have followed the tutorial called web lesson, in case I tried to find a solutions on internet but didn't help me to solve my problem. Here is my HTML segments:
<table id="datatables-example" class="table table-striped table-bordered" width="100%" cellspacing="0">
<thead>
<tr>
<th>Appointment ID</th>
<th>Doctor Name</th>
<th>Specialization</th>
<th>Patient Name</th>
<th>Fees</th>
<th>Appointment Date</th>
<th>Appointment Time</th>
<th>Status</th>
<th class="text-right">Action</th>
</tr>
</thead>
</table>
Below is the Ajax segments:
<script>
$(document).ready(function() {
load_data();
function load_data(){
var datatable= $('#datatables-example').DataTable({
"processing": true,
"serverSide": true,
"order" :[],
"ajax" : {
url: "sidebar/apt_table admin.php", // Url to which the request is send
method: "POST", // Type of request to be send, called as method
}
});
}
});
</script>
The apt_table admin.php page should be:
<?php
session_start();
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$conn = new mysqli("localhost", "root", "", "hmsproject");
$conn->set_charset("utf8mb4");
} catch(Exception $e) {
error_log($e->getMessage());
exit('Error connecting to database'); //Should be a message a typical user could understand
}
$columns= array('apt_id','doctor_name','specilization','patient_name','fees','apt_date','apt_time','admin_status');
$query="SELECT * FROM appointment as a,users as u WHERE a.user_id= u.user_id ORDER BY apt_id DESC";
if(isset($_POST["search"]["value"])){
$query .= '
WHERE apt_id LIKE "%'.$_POST["search"]["value"].'%"
OR doctor_name LIKE "%'.$_POST["search"]["value"].'%"
OR specilization LIKE "%'.$_POST["search"]["value"].'%"
OR patient_name LIKE "%'.$_POST["search"]["value"].'%"
OR fees LIKE "%'.$_POST["search"]["value"].'%"
OR apt_date LIKE "%'.$_POST["search"]["value"].'%"
OR apt_time LIKE "%'.$_POST["search"]["value"].'%"
OR admin_status LIKE "%'.$_POST["search"]["value"].'%"
';
}
if (isset($_POST["order"])) {
$query .= ' ORDER BY '.$columns[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].' ';
}else{
$query .= ' ORDER BY apt_id DESC';
}
$query1='';
if ($_POST["length"] != -1) {
$query1 = 'LIMIT '.$_POST['start'] .' , '.$_POST['length'];
}
$number_filter_row= mysqli_num_rows(mysqli_query($conn,$query));
$result =mysqli_query($conn,$query.$query1);
$data=array();
while($row = mysqli_fetch_array($result))
{
$sub_array =array();
$sub_array[] = '<td> '. $row["apt_id"].' </td>';
$sub_array[] ='<td> '. $row["doctor_name"].' </td>';
$sub_array[] ='<td> '. $row["specilization"].' </td>';
$sub_array[] ='<td> '. $row["patient_name"].' </td>';
$sub_array[] ='<td> '. $row["fees"].' </td>';
$sub_array[] ='<td> '. $row["apt_date"].' </td>';
$sub_array[] ='<td> '. $row["apt_time"].' </td>';
if($row["admin_status"]=="0") {
$sub_array[] ='<td> <span class="custom-badge status-red">Cancel</span>';
} else if($row["admin_status"]=="1") {
$sub_array[] ='<td> <span class="custom-badge status-green">Active</span>';
} else {
$sub_array[] ='<td> <span class="custom-badge status-blue">Pending</span>';
}
$sub_array[] = '<td class="text-right">
<div class="dropdown dropdown-action">
<i class="fa fa-ellipsis-v"></i>
<div class="dropdown-menu dropdown-menu-right">
<!-- <a class="dropdown-item" href="edit-appointment.php"><i class="fa fa-pencil m-r-5"></i> Edit</a> -->
<a class="dropdown-item" href="" data-toggle="modal" id="rep1" data_id= '.$row['apt_id'] .' data-target="#active_appointment"><i class="fa fa-trash-o m-r-5"></i> Active</a>
<a class="dropdown-item" href="" data-toggle="modal" id="rep2" data_id='. $row['apt_id'].' data-target="#delete_appointment"><i class="fa fa-trash-o m-r-5"></i> Delete</a>
</div>
</div>
</td>';
$data[]=$sub_array;
}
function get($conn)
{
$query="SELECT * FROM appointment as a,users as u WHERE a.user_id= u.user_id ORDER BY apt_id DESC";
$result =mysqli_query($conn,$query);
return mysqli_num_rows($result);
}
$output= array(
"draw" => intval($_POST['draw']),
"recordsTotal" => get($conn),
"recordsFiltered" => $number_filter_row,
"data" => $data
);
echo json_encode($output);
?>
I don't know where I went wrong. Please help me. Thanks in advance.
to implement server-side ajax datatable your script should return json only you are sending html with some <tr> and <td>
Refer: https://datatables.net/examples/data_sources/server_side
in above example source is giving json output only.
So, try to fix your apt_table admin.php
Try this little debug (RETRIEVE THE COMMA AT THE END "post" )
"ajax" : {
url: "sidebar/apt_table admin.php",
method: "POST"
}
Related
So I've been using php for a while now but recently, I've decided to use ajax so I can view live data and I don't have to refresh the page to see changes in the database. And I created a page and the fetch function works but when it's in the table, the table functions doesn't work. At the bottom of the table it says it's showing 0 out of 0 entries and the sort by function and the show {limit} function doesn't work either. It's like somehow the table div doesn't read the data inside.
Here's my code:
<div class="body" >
<div class="table-responsive">
<table class="table table-bordered table-striped table-hover js-basic-example dataTable" >
<thead>
<tr>
<th width="155">Action</th>
<th width="90">LRN</th>
<th width="45">Level</th>
<th>Name</th>
<th width="15">Gender</th>
<th width="65">Type</th>
<th width="110" style="font-size: 14px!important;">Date Enrolled</th>
<th width="40">Card</th>
</tr>
</thead>
<tbody id="live-data">
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready( function() {
function fetch_data() {
$.ajax({
url:"fetch.php",
method:"POST",
success:function(data){
console.log(data);
$('#live-data').html(data);
}
});
}
fetch_data();
});
</script>
Here's fetch.php
<?php
include('../global/db.php');
$output = '';
$query ="SELECT * FROM students WHERE status = '0' ORDER BY date_enrolled DESC";
$result = mysqli_query($db, $query);
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)){
$date_enrolled = $row['date_enrolled'];
$card = $row['card'];
$stud_birth = $row['stud_birth'];
$age = date('Y', strtotime($stud_birth)); $year = date('Y '); $age = (int)$age; $year = (int)$year;
$sage = $year - $age;
$output .= '
<tr>
<td>
<button type="button" class="btn bg-cyan btn-xs waves-effect" data-toggle="modal" data-target="#'.$row['stud_id'].'">
<i class="material-icons">search</i>
<span>Profile</span>
</button> <button type="button" class="btn bg-orange btn-xs waves-effect" data-toggle="modal" data-target="#'.$row['stud_id'].''.$row['stud_id'].'">
<i class="material-icons">search</i>
<span>Approve</span>
</button>
</td>
<td>'.$row['stud_lrn'].'</td>
<td>'.$row['stud_grade'].'</td>
<td>'.$row['stud_lname'].', '.$row['stud_fname'].' '.$row['stud_mname'].'</td>
<td>'.$row['stud_gender'].'</td>
<td>'.$row['stud_type'].'</td>
<td style="font-size: 12px!important;">'.$date_enrolled = date("M-d-Y g:i A", strtotime($date_enrolled)).'</td>
<td>';
if ($card == "") {
$output .= '
<center>N/A</center>';
}
else {
$output .= '
<center><a target="_blank" href="../image-gallery/20.jpg" data-sub-html="Demo Description">
<img class="img-responsive" src="../image-gallery/thumb/thumb-20.jpg" style="width: 70px; height: 35px;"></a></center>';
}
$output .= '
</td>
</tr>';
}
}
else {
$output .= '
<tr>
<td colspan="4">Data not Found</td>
</tr>';
}
echo $output;
?>
I think you are using dataTable jquery library . Problem is its not right way to use datatabe . you need a json format out from backend like as
{
"data": [
[
"Tiger Nixon",
"System Architect",
"Edinburgh",
"5421",
"2011/04/25",
"$320,800"
],
[
"Garrett Winters",
"Accountant",
"Tokyo",
"8422",
"2011/07/25",
"$170,750"
],
}
Don't forget to warp with {data:[]} object
after then simply use in ajax
$(document).ready(function() {
$('#live-data').DataTable( {
"ajax": 'fetch.php'
} );
} );
For more ...
https://datatables.net/examples/data_sources/ajax.html
I'm using this CRUD tutorial https://www.webslesson.info/2017/01/php-pdo-ajax-crud-with-data-tables-and-bootstrap-modals.html to make some tests and i would like to improve it including 2 columns related to another tables on MySql.
I'm working with those tutorial files below:
One php file that fetch data to display on DataTables (fetch.php);
One index.php file;
One table that call "Users" and it has 4 columns:
Users table
-------------------------------------
id | first_name | last_name | image
I created 2 tables to relate with "Users" table. Are they:
"type_service" table with columns ("typeID" and "type") and
"categories" table with columns ("categoryID" and "category").
On "users" table i included 2 columns that call "type_fk" and "category_fk" where "fk" is foreign key:
Users table
----------------------------------
id | first_name | last_name | image | type_fk | category_fk
When columns were created they were related to "users" table where relationships works perfectly.
After this i included an INNER JOIN query in fetch.php file like below:
$query .= "SELECT users.*, type_service.type, categories.category
FROM users INNER JOIN type_service ON users.type_fk = type_service.typeID
INNER JOIN categories ON users.category_fk = categories.categoryID ";
Fetch.php file:
<?php
include('db.php');
include('function.php');
$query = '';
$output = array();
$query .= "SELECT users.*, type_service.type, categories.category
FROM users
INNER JOIN type_service ON users.type_fk = type_service.typeID
INNER JOIN categories ON users.category_fk = catgories.categoryID
";
if(isset($_POST["search"]["value"]))
{
$query .= 'WHERE first_name LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR last_name LIKE "%'.$_POST["search"]["value"].'%" ';
}
if(isset($_POST["order"]))
{
$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
$query .= 'ORDER BY id DESC ';
}
if($_POST["length"] != -1)
{
$query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connection->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
$image = '';
if($row["image"] != '')
{
$image = '<img src="upload/'.$row["image"].'" class="img-thumbnail" width="50" height="35" />';
}
else
{
$image = '';
}
$sub_array = array();
$sub_array[] = $image;
$sub_array[] = $row["first_name"];
$sub_array[] = $row["last_name"];
$sub_array[] = $row["type"];
$sub_array[] = $row["category"];
$sub_array[] = '<button type="button" name="update" id="'.$row["id"].'" class="btn btn-warning btn-xs update">Update</button>';
$sub_array[] = '<button type="button" name="delete" id="'.$row["id"].'" class="btn btn-danger btn-xs delete">Delete</button>';
$data[] = $sub_array;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $filtered_rows,
"recordsFiltered" => get_total_all_records(),
"data" => $data
);
echo json_encode($output);
?>
After included INNER JOIN query on code above, i included 2 sub_array in the same file (fetch.php) like below:
$sub_array[] = $row["type"];
$sub_array[] = $row["category"];
Where code stay like this:
$sub_array = array();
$sub_array[] = $image;
$sub_array[] = $row["type"];
$sub_array[] = $row["category"];
$sub_array[] = $row["first_name"];
$sub_array[] = $row["last_name"];
$sub_array[] = '<button type="button" name="update" id="'.$row["id"].'" class="btn btn-warning btn-xs update">Update</button>';
$sub_array[] = '<button type="button" name="delete" id="'.$row["id"].'" class="btn btn-danger btn-xs delete">Delete</button>';
$data[] = $sub_array;
When the code above is executed, the index.php page show data through html code below:
<body>
<div class="container box">
<h1 align="center">PHP PDO Ajax CRUD with Data Tables and Bootstrap Modals</h1>
<br />
<div class="table-responsive">
<br />
<div align="right">
<button type="button" id="add_button" data-toggle="modal" data-target="#userModal" class="btn btn-info btn-lg">Add</button>
</div>
<br /><br />
<table id="user_data" class="table table-bordered table-striped">
<thead>
<tr>
<th width="10%">Image</th>
<th width="10%">Type</th>
<th width="15%">Category</th>
<th width="15%">First Name</th>
<th width="15%">Last Name</th>
<th width="10%">Edit</th>
<th width="10%">Delete</th>
</tr>
</thead>
</table>
</div>
</div>
</body>
And when i refresh index.php page, DataTable return an invalid JSON response like image below:
https://imgur.com/DeLCZdV
In this case if i remove the query line:
INNER JOIN categories ON users.category_fk = categories.category
The DataTable return all data but show Category column ID instead of the category name. The image below can show this:
https://imgur.com/KpsBsiF
But if i reinclude:
INNER JOIN categories ON users.category_fk = categories.categoryID
DataTables display the error below again:
DataTables warning: table id=user_data - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
What i see is when i include just one INNER JOIN query the DataTable display all data but if i include one more INNER JOIN, DataTable return an invalid JSON response even including the respective sub_arrays.
$sub_array[] = $row["type"];
$sub_array[] = $row["category"];
In this case what can i do to improve this code to show name instead of ID?
If you wanna have only 1 table you can combine type_service and categories like that
type_service_categories
id | type | name
where type is service or category and name is service_type or category name
...but this will not resolve your problem because you have to to write 2 inner join statements in the query anyway.
your error is possible to come from
$result = $statement->fetchAll();
Can you post db.php? or you can try:
foreach($row as $rkey => $rvalue){
$sub_array[] = $row[$rkey];}
to see what fields your query is returning when you call fetchAll() function or how they are fetch and return.
Or try developer option in chrome to see exactly json error.
Guys I'm driving crazy with this code:
I'm trying to populate my datagrid with the datatable plugin but I'm not understanding why it doesn't working. I have a message whith:
DataTables warning: table id=item_data - Invalid JSON response.
$(document).ready(function() {
$('#item_data').DataTable( {
"processing": true,
"serverSide": true,
"ajax":{
url:"item_fetch.php",
type:"POST"
},
"columnDefs":[
{
"targets":[7, 8, 9],
"orderable":false,
},
],
"pageLength": 10
});
});
<script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<table id="item_data" class="table table-bordered table-striped">
<thead>
<tr>
<th>Item Code</th>
<th>Item Description</th>
<th>Product Line</th>
<th>Purchase Standard Cost</th>
<th>Last Receipt</th>
<th>Status</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<?php //include("item_list.php"); ?>
</table>
Theoretically item_fetch execute the query to populate my datagrid but, the java code doesn't reading the table id.
Above my item_fetch code
<?php
//item_fetch.php
include('phpfunc/database_connection.php');
include('phpfunc/function.php');
$query = '';
$output = array();
$query .= "
SELECT * FROM item
INNER JOIN i_prodline ON i_prodline,prodline_id = item.item_prodline
";
if(isset($_POST["search"]["value"]))
{
$query .= 'WHERE i_prodline.prodline_cod LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR i_prodline.prodline_desc LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR item.item_code LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR item.item_desc LIKE "%'.$_POST["search"]["value"].'%" ';
}
if(isset($_POST['order']))
{
$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
$query .= 'ORDER BY item_code DESC ';
}
if($_POST['length'] != -1)
{
$query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
$status = '';
if($row['item_status'] == 'active')
{
$status = '<span class="label label-success">Active</span>';
}
else
{
$status = '<span class="label label-danger">Inactive</span>';
}
$sub_array = array();
$sub_array[] = $row['item_code'];
$sub_array[] = $row['item_desc'];
$sub_array[] = $row['prodline_cod'];
$sub_array[] = $row['item_standardcost'];
$sub_array[] = $row['item_datareceipt'];
$sub_array[] = $status;
$sub_array[] = '<button type="button" name="view" id="'.$row["item_id"].'" class="btn btn-info btn-xs view">View</button>';
$sub_array[] = '<button type="button" name="update" id="'.$row["item_id"].'" class="btn btn-warning btn-xs update">Update</button>';
$sub_array[] = '<button type="button" name="delete" id="'.$row["item_id"].'" class="btn btn-danger btn-xs delete" data-status="'.$row["item_status"].'">Delete</button>';
$data[] = $sub_array;
}
function get_total_all_records($connect)
{
$statement = $connect->prepare('SELECT * FROM item');
$statement->execute();
return $statement->rowCount();
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $filtered_rows,
"recordsFiltered" => get_total_all_records($connect),
"data" => $data
);
echo json_encode($output);
?>
Please how can I fix it? I'm not understanding where is the mistake.
Looks like you left some debugging echo in your php code that is producing invalid JSON (thus the message from Datatable API).
Please comment line 32 in your php code.
Here is how it should look like later:
<?php
//item_fetch.php
include('phpfunc/database_connection.php');
include('phpfunc/function.php');
$query = '';
$output = array();
$query .= "
SELECT * FROM item
INNER JOIN i_prodline ON i_prodline,prodline_id = item.item_prodline
";
if(isset($_POST["search"]["value"]))
{
$query .= 'WHERE i_prodline.prodline_cod LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR i_prodline.prodline_desc LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR item.item_code LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR item.item_desc LIKE "%'.$_POST["search"]["value"].'%" ';
}
if(isset($_POST['order']))
{
$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
$query .= 'ORDER BY item_code DESC ';
}
//forgot to comment out debug echos
//echo $query;
if($_POST['length'] != -1)
{
$query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
$status = '';
if($row['item_status'] == 'active')
{
$status = '<span class="label label-success">Active</span>';
}
else
{
$status = '<span class="label label-danger">Inactive</span>';
}
$sub_array = array();
$sub_array[] = $row['item_code'];
$sub_array[] = $row['item_desc'];
$sub_array[] = $row['prodline_cod'];
$sub_array[] = $row['item_standardcost'];
$sub_array[] = $row['item_datareceipt'];
$sub_array[] = $status;
$sub_array[] = '<button type="button" name="view" id="'.$row["item_id"].'" class="btn btn-info btn-xs view">View</button>';
$sub_array[] = '<button type="button" name="update" id="'.$row["item_id"].'" class="btn btn-warning btn-xs update">Update</button>';
$sub_array[] = '<button type="button" name="delete" id="'.$row["item_id"].'" class="btn btn-danger btn-xs delete" data-status="'.$row["item_status"].'">Delete</button>';
$data[] = $sub_array;
}
function get_total_all_records($connect)
{
$statement = $connect->prepare('SELECT * FROM item');
$statement->execute();
return $statement->rowCount();
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $filtered_rows,
"recordsFiltered" => get_total_all_records($connect),
"data" => $data
);
echo json_encode($output);
?>
I have a scenario in user management section where before creating a user, I need to make sure the username already exists or not. On the successful insertion success message is shown after form submit but I can not figure out how to show the warning alert if I try to create a new user with existing username. In order to check if username already exists or not I have checked the row in user table, the code I tried is given below...
$sql="select * from user where username='$username'";
$result=mysqli_query($connection, $sql);
$row_no=mysqli_num_rows($result);
/*if($row_no<1){*/
if($_POST["user_id"] != '')
{
$query = "
UPDATE user
SET fullname='$fullname',
user_role='$user_role',
username='$username',
password = '$password',
branch_id = '$branch'
WHERE user_id='".$_POST["user_id"]."'";
$message = 'Data Updated';
if($_SESSION['user_id']==$_POST["user_id"]){
$_SESSION['username']=$username;
$_SESSION['user_role']=$user_role;
$_SESSION['fullname']=$fullname;
}
} else{
$query = "
INSERT INTO user(fullname, user_role, username, password, branch_id,registered_date)
VALUES('$fullname', '$user_role', '$username', '$password', '$branch','$registered_date')
";
}
if(mysqli_query($connection, $query))
{
$select_query = "SELECT * FROM user ORDER BY user_id DESC";
$result = mysqli_query($connection, $select_query);
$output .= '
<table style="background-color:#FFF;" id="employee_data" class="table table-striped table-bordered">
<thead>
<tr>
<th>User ID</th>
<th>Fullname</th>
<th>User Role</th>
<th>Username</th>
<th>Password</th>
<th>Branch</th>
<th>Registered Date</th>
<th>Action</th>
</tr>
</thead>
';
while($row = mysqli_fetch_array($result))
{
$output .='
<tr>
<td>'.$row["user_id"].'</td>
<td>'.$row["fullname"].' </td>
<td>'.$row["user_role"].'</td>
<td>'.$row["username"].'</td>
<td>'.$row["password"].'</td>
<td>'.$row["branch_id"].'</td>
<td>'.$row["registered_date"].'</td>
<td>
<Button id="'.$row["user_id"].'" class="btn btn-warning btn-xs edit_data">
<i class="fa fa-edit "></i></Button>  ' ;
if($_SESSION['user_id']!=$row["user_id"]) {
$output .='<a id="'.$row["user_id"].'" class="btn btn-danger btn-xs
delete"><i class="fa fa-times"></i></a>';
}
$output .= '</td></tr>';
}
$output .= '
</table>
<div id="success-alert" class="alert alert-success fade in m-b-15">
<strong>Success!</strong>
Data Updated.
<span class="close" data-
dismiss="alert">×</span>
</div>
<script>$("#success-alert").fadeTo(2000,
500).slideUp(500, function(){
$("#success-alert").slideUp(600); });</script>
';
}
echo $output;
}
To prevent a submit u can use...
$(document).ready(function(e){
e.preventDefault();
// Rest of your code...
});
And to show error messages...
You can make an array in your handler and adding an error in the array
After all the validations do one more validation on your array filled with the errors.
When there are errors you can display a div and fill those with your arrays.
I have this server side table that works fine, except it has modals, but I need to open another PHP edit page(not as modal), linked to the row-id selected.
</div>
<div class="table-responsive">
<table id="users_data" class="table table-bordered table-striped">
<thead>
<tr>
<th data-column-id="id" data-type="numeric">No</th>
<th data-column-id="idno">Id No</th>
<th data-column-id="surname">Surname</th>
<th data-column-id="firstname">Firstname</th>
<th data-column-id="category_name">Category</th>
<th data-column-id="age">Age</th>
<th data-column-id="commands" data-formatter="commands" data-sortable="false">Commands</th>
</tr>
</thead>
</table>
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
$('#add_button').click(function(){
$('#users_form')[0].reset();
$('.modal-title').text("Add New Users");
$('#action').val("Add");
$('#operation').val("Add");
});
var usersTable = $('#users_data').bootgrid({
ajax: true,
rowSelect: true,
post: function()
{
return{
id: "b0df282a-0d67-40e5-8558-c9e93b7befed"
};
},
url: "fetch.php",
formatters: {
"commands": function(column, row)
{
return "<button type='button' class='btn btn-warning btn-xs update' data-row-id='"+row.id+"'>Edit</button>" +
" <button type='button' class='btn btn-danger btn-xs delete' data-row-id='"+row.id+"'>Delete</button>";
}
}
});
Where the buttons are, I need something like this:
<td><span class="glyphicon glyphicon-pencil" aria-hidden="true" </span><b><font size="3" color="red"</font> Edit<b></td>
Currently it uses this modal info:
$(document).on("loaded.rs.jquery.bootgrid", function()
{
usersTable.find(".update").on("click", function(event)
{
var id = $(this).data("row-id");
$.ajax({
//url:"update2.php",
url:"fetch_single_entries.php",
method:"POST",
data:{id:id},
dataType:"json",
success:function(data)
{
$('#usersModal').modal('show');
$('#categories').val(data.categories);
$('#idno').val(data.idno);
$('#surname').val(data.surname);
$('#firstname').val(data.firstname);
$('#age').val(data.age);
$('.modal-title').text("Edit User");
$('#id').val(id);
$('#action').val("Edit");
$('#operation').val("Edit");
}
});
});
});
The fetch.php for the table data looks like this:
<?php
//fetch.php
include("connection.php");
$query = '';
$data = array();
$records_per_page = 10;
$start_from = 0;
$current_page_number = 0;
if(isset($_POST["rowCount"]))
{
$records_per_page = $_POST["rowCount"];
}
else
{
$records_per_page = 10;
}
if(isset($_POST["current"]))
{
$current_page_number = $_POST["current"];
}
else
{
$current_page_number = 1;
}
$start_from = ($current_page_number - 1) * $records_per_page;
$query .= "
SELECT
users.id,
tblcategories.category_name,
users.idno,users.surname,users.firstname,
users.age FROM users
INNER JOIN tblcategories
ON tblcategories.category_id = users.category_id ";
if(!empty($_POST["searchPhrase"]))
{
$query .= 'WHERE (users.id LIKE "%'.$_POST["searchPhrase"].'%" ';
$query .= 'OR tblcategories.category_name LIKE "%'.$_POST["searchPhrase"].'%" ';
$query .= 'OR users.idno LIKE "%'.$_POST["searchPhrase"].'%" ';
$query .= 'OR users.surname LIKE "%'.$_POST["searchPhrase"].'%" ';
$query .= 'OR users.firstname LIKE "%'.$_POST["searchPhrase"].'%" ';
$query .= 'OR users.age LIKE "%'.$_POST["searchPhrase"].'%" ) ';
}
$order_by = '';
if(isset($_POST["sort"]) && is_array($_POST["sort"]))
{
foreach($_POST["sort"] as $key => $value)
{
$order_by .= " $key $value, ";
}
}
else
{
$query .= 'ORDER BY users.id DESC ';
}
if($order_by != '')
{
$query .= ' ORDER BY ' . substr($order_by, 0, -2);
}
if($records_per_page != -1)
{
$query .= " LIMIT " . $start_from . ", " . $records_per_page;
}
//echo $query;
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result))
{
$data[] = $row;
}
$query1 = "SELECT * FROM users";
$result1 = mysqli_query($connection, $query1);
$total_records = mysqli_num_rows($result1);
$output = array(
'current' => intval($_POST["current"]),
'rowCount' => 10,
'total' => intval($total_records),
'rows' => $data
);
echo json_encode($output);
?>
Please assist this novice programmer about how to adjust the code.
Sounds like you just want to convert an jquery ajax edit thing on a modal dialogue into an actual HTML edit page. Replace all of that jquery with just a link to a new page you create, and on that page just have a form with the stuff in it. The first thing you'll want is to check if it's a GET or a POST request - if GET, query from the database for the values and display the standard HTML form. If it's a POST, update the database with the new values (after optionally doing some processing).
Hopefully that's the question you're asking? If so, sorry the answer is so broad, but the question is kind of broad too. Feel free to clarify further if there's a specific problem you're encountering trying to get the above to work.
Here is how to add the links:
return "<button type=\"button\" class=\"btn btn-xs btn-warning\" data-row-id=\"" + row.id + "\"><span class=\"glyphicon glyphicon-pencil\"></span></button> " +
"<button type=\"button\" class=\"btn btn-xs btn-danger\" data-row-id=\"" + row.id + "\"><span class=\"glyphicon glyphicon-trash\"></span></button>";