datatable and jquery doesn't working - php

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);
?>

Related

PHP AJAX - Datatable not searching (glitch/error)

I am displaying the data in a table which uses Datatable function. It's displaying data correctly using this php code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "security_db";
$connection = new PDO("mysql:host=$servername;dbname=$database",$username,$password);
$connection->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
function get_total_violations() {
$servername = "localhost";
$username = "root";
$password = "";
$database = "security_db";
$connection = new PDO("mysql:host=$servername;dbname=$database",$username,$password);
$statement = $connection->prepare("SELECT * FROM traffic_violations");
$statement->execute();
return $statement->rowCount();
}
$query = '';
$output = array();
$query = "SELECT * FROM traffic_violations";
$statement = $connection->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row) {
$traffic_doc = '';
if($row["violationStatement"] != '') {
$traffic_doc = '<img src="uploads/traffic_violations/'.$row["violationStatement"].'" class="img-thumbnail" width="50" height="35" />';
} else {
$traffic_doc = '';
}
$sub_array = array();
$sub_array[] = $row["plateNumber"];
$sub_array[] = $row["carModel"];
$sub_array[] = $row["carColor"];
$sub_array[] = $row["violationType"];
$sub_array[] = $row["violationLocation"];
$sub_array[] = $row["violationDateTime"];
$sub_array[] = $traffic_doc;
$sub_array[] = $row["cccEmployee"];
// $sub_array[] = $row["ownerGender"];
// $sub_array[] = $row["workingShift"];
// $sub_array[] = $row["violationAction"];
$sub_array[] = '<a href="javascript:void(0)" name="update" id="'.$row['id'].'">
<i class="fas fa-edit"></i>
</a>';
$sub_array[] = '<a href="javascript:void(0)" name="delete" id="'.$row['id'].'">
<i class="fas fa-trash-alt"></i>
</a>';
$data[] = $sub_array;
}
$output = array(
//"draw" => intval($_POST["draw"]),
//"recordsTotal" => $filtered_rows,
"recordsFiltered" => get_total_violations(),
"data" => $data
);
echo json_encode($output);
?>
I also use Ajax:
$(document).ready(function() {
$("#btn_save").click(function() {
$("#traffic_violation_form")[0].reset();
$(".modal-title").text("Add New Violation");
$("#traffic_action").val("Add");
$("#traffic_operation").val("Add");
$("#traffic_doc").html('');
});
var dataTable = $('.violation_data').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "/traffic-fetch",
"type": "POST",
}
});
$(document).on('submit', '#traffic_violation_form', function(e){
e.preventDefault();
var plateNumber = $("#plate_number").val();
var carModel = $("#car_model").val();
var carColor = $("#car_color").val();
var ownerGender = $("#owner_gender").val();
var violationType = $("#violation_type").val();
var violationLocation = $("#violation_location").val();
var workingShift = $("#working_shift").val();
var violationAction = $("#violation_action").val();
var violationStatement = $("#traffic_doc").val().split('.').pop().toLowerCase();
var cccEmployee = $("#ccc_employee").val();
if(violationStatement != '') {
if( JQuery.inArray(violationStatement, ['jpg', 'jpeg', 'JPG', 'JPEG', 'png', 'PNG', 'webp', 'WEBP']) == -1 ) {
alert('Invalid file type.');
$("#traffic_doc").val();
return false;
}
}
if( plateNumber !='' && carModel !='' && carColor !='' && ownerGender !='' && violationType !='' && violationLocation !='' && workingShift !='' && violationAction !='' && cccEmployee !='') {
$.ajax({
url: "/insert-traffic",
method: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data) {
$("#traffic_violation_form")[0].reset();
$("#trafficModal").modal('hide');
dataTable.ajax.reload();
}
});
}
else {
alert('Nothing should left empty!');
}
});
});
The problem I have is that when I type in the search field, no data is being filtered according to the inputted search. I tried removing the scripts but the glitch/error still there.
What should happen: When a text is typed in the search, all other data should hide and only display the typed keyword.
Check gif:
In the scripts I am including these also:
<!-- Datatables -->
<script src="<?php echo $PATH?>/vendor/datatables.net/js/jquery.dataTables.min.js"></script>
<script src="<?php echo $PATH?>/vendor/datatables.net-bs4/js/dataTables.bootstrap4.min.js"></script>
<script src="<?php echo $PATH?>/vendor/datatables.net-buttons/js/dataTables.buttons.min.js"></script>
<script src="<?php echo $PATH?>/vendor/datatables.net-buttons-bs4/js/buttons.bootstrap4.min.js"></script>
<script src="<?php echo $PATH?>/vendor/datatables.net-select/js/dataTables.select.min.js"></script>
And this is the HTML:
<div class="table-responsive">
<table class="violation_data table align-items-center table-flush table-striped">
<thead class="thead-light">
<tr>
<th>Plate #</th>
<th>Vehicle Model</th>
<th>Vehicle Color</th>
<th>Violation</th>
<th>Location</th>
<th>Happened at</th>
<th>Document</th>
<th>CCC Employee</th>
<th></th>
<th></th>
</tr>
</thead>
<tfoot class="thead-light">
<tr>
<th>Plate #</th>
<th>Vehicle Model</th>
<th>Vehicle Color</th>
<th>Violation</th>
<th>Location</th>
<th>Happened at</th>
<th>Document</th>
<th>CCC Employee</th>
<th></th>
<th></th>
</tr>
</tfoot>
</table>
</div>
I solved it!
I just changed the syntax to the following:
$query .= " WHERE ";
if(isset($_POST["search"]["value"]))
{
$query .= '(plateNumber LIKE "%'.$_POST["search"]["value"].'%"';
$query .= 'OR carModel LIKE "%'.$_POST["search"]["value"].'%"';
$query .= 'OR carColor LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR violationType LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR violationLocation LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR ownerGender LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR violationDateTime LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR cccEmployee LIKE "%'.$_POST["search"]["value"].'%")';
}
I added ( before plateNumber and ) after cccEmployee
and changed $query = " "; to $query .= " WHERE ";

Datatables warning table id=datatables-example - invalid json response

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"
}

How to improve my php sub_array code using INNER JOIN to display data on DataTables?

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.

Not Able to access MySQL data through php function

I've added clients in clients.php sown on the following screenshot:
UPDATE: If I add new client from manange_sale page, The List Shows up soon after!
When I try to access them in another page through this function:
function get_client_info($client_id, $term) {
global $db;
$query = "SELECT * from clients WHERE client_id='".$client_id."'";
$result = $db->query($query) or die($db->error);
$row = $result->fetch_array();
return $row[$term];
}
It just does not show any clients list on that page:
Please help me resolve this issue.
Note: Same script is working perfectly on Online host but causing issues in localhost.
Rest of the client class:
<?php
//Notes Class
class Client {
public $full_name;
public $business_title;
public $mobile;
public $phone;
public $address;
public $city;
public $state;
public $zipcode;
public $country;
public $email;
public $price_level;
public $notes;
function get_client_info($client_id, $term) {
global $db;
$query = "SELECT * from clients WHERE client_id='".$client_id."'";
$result = $db->query($query) or die($db->error);
$row = $result->fetch_array();
return $row[$term];
}//get user email ends here.
function add_client($full_name, $business_title, $mobile, $phone, $address, $city, $state, $zipcode, $country, $email, $price_level, $notes) {
global $db;
$query = "SELECT * from clients WHERE full_name='".$full_name."' AND store_id='".$_SESSION['store_id']."'";
$result = $db->query($query) or die($db->error);
$num_rows = $result->num_rows;
if($num_rows > 0) {
return 'A client with same name already exists.';
} else {
$query = "INSERT into clients(client_id, full_name, business_title, mobile, phone, address, city, state, zipcode, country, email, price_level, notes, store_id)
VALUES(NULL, '".$full_name."', '".$business_title."', '".$mobile."', '".$phone."', '".$address."', '".$city."', '".$state."', '".$zipcode."', '".$country."', '".$email."', '".$price_level."', '".$notes."', '".$_SESSION['store_id']."')
";
$result = $db->query($query) or die($db->error);
$_SESSION['cn_id'] = $db->insert_id;
return 'Client added successfuly.';
}
}//add warehouse ends here.
function set_client($client_id) {
global $db;
$query = 'SELECT * from clients WHERE client_id="'.$client_id.'" AND store_id="'.$_SESSION['store_id'].'"';
$result = $db->query($query) or die($db->error);
$row = $result->fetch_array();
extract($row);
$this->full_name = $full_name;
$this->business_title = $business_title;
$this->mobile = $mobile;
$this->phone = $phone;
$this->address = $address;
$this->city = $city;
$this->state = $state;
$this->zipcode = $zipcode;
$this->country = $country;
$this->email = $email;
$this->price_level = $price_level;
$this->notes = $notes;
}//Set Warehouse ends here..
function update_client($client_id, $full_name, $business_title, $mobile, $phone, $address, $city, $state, $zipcode, $country, $email, $price_level, $notes) {
global $db;
$query = 'UPDATE clients SET
full_name = "'.$full_name.'",
business_title = "'.$business_title.'",
mobile = "'.$mobile.'",
phone = "'.$phone.'",
address = "'.$address.'",
city = "'.$city.'",
state = "'.$state.'",
zipcode = "'.$zipcode.'",
country = "'.$country.'",
email = "'.$email.'",
price_level = "'.$price_level.'",
notes = "'.$notes.'"
WHERE client_id="'.$client_id.'" AND store_id="'.$_SESSION['store_id'].'"';
$result = $db->query($query) or die($db->error);
return 'Client updated Successfuly!';
}//update user level ends here.
function list_clients() {
global $db;
$query = 'SELECT * from clients WHERE store_id="'.$_SESSION['store_id'].'" ORDER by full_name ASC';
$result = $db->query($query) or die($db->error);
$content = '';
$count = 0;
while($row = $result->fetch_array()) {
extract($row);
$count++;
if($count%2 == 0) {
$class = 'even';
} else {
$class = 'odd';
}
$content .= '<tr class="'.$class.'">';
$content .= '<td>';
$content .= $client_id;
$content .= '</td><td>';
$content .= $full_name;
$content .= '</td><td>';
$content .= $business_title;
$content .= '</td><td>';
$content .= $mobile;
$content .= '</td><td>';
$content .= $phone;
$content .= '</td><td>';
$content .= $address.' '.$city.' '.$state.' '.$zipcode.' '.$country;
$content .= '</td><td>';
$content .= $email;
$content .= '</td><td>';
$content .= $price_level;
$content .= '</td><td>';
$content .= currency_format($this->get_client_balance($client_id));
$content .= '</td>';
if(partial_access('admin')) {
$content .= '<td><form method="post" name="edit" action="manage_client.php">';
$content .= '<input type="hidden" name="edit_client" value="'.$client_id.'">';
$content .= '<input type="submit" class="btn btn-default btn-sm" value="Edit">';
$content .= '</form>';
$content .= '</td><td>';
$content .= '<form method="post" name="delete" onsubmit="return confirm_delete();" action="">';
$content .= '<input type="hidden" name="delete_client" value="'.$client_id.'">';
$content .= '<input type="submit" class="btn btn-default btn-sm" value="Delete">';
$content .= '</form>';
$content .= '</td>';
}
$content .= '</tr>';
unset($class);
}//loop ends here.
echo $content;
}//list_notes ends here.
function delete_client($client_id) {
global $db;
$query = "SELECT * FROM customer_log WHERE client_id='".$client_id."'";
$result = $db->query($query) or die($db->error);
$num_rows = $result->num_rows;
if($num_rows > 0) {
return 'Please delete sale invoices, receivings, return invoices, return payments for related client first.';
} else {
$query = "DELETE FROM clients WHERE client_id='".$client_id."'";
$result = $db->query($query) or die($db->error);
return 'Client deleted successfuly!';
}
}//delete client ends here.
function client_options($client_id) {
global $db;
$query = 'SELECT * from clients WHERE store_id="'.$_SESSION['store_id'].'" ORDER by full_name ASC';
$result = $db->query($query) or die($db->error);
$options = '';
if($client_id != '') {
while($row = $result->fetch_array()) {
if($client_id == $row['client_id']) {
$options .= '<option selected="selected" value="'.$row['client_id'].'">'.$row['full_name'].' ('.$row['mobile'].')</option>';
} else {
$options .= '<option value="'.$row['client_id'].'">'.$row['full_name'].' ('.$row['mobile'].')</option>';
}
}
} else {
while($row = $result->fetch_array()) {
$options .= '<option value="'.$row['client_id'].'">'.$row['full_name'].' ('.$row['mobile'].')</option>';
}
}
return $options;
}//vendor options ends here.
function add_log($datetime, $client_id, $transaction_type, $type_table_id) {
global $db;
$query = "INSERT into customer_log(customer_log_id, datetime, client_id, transaction_type, type_table_id, store_id) VALUES(NULL, '".$datetime."', '".$client_id."', '".$transaction_type."', '".$type_table_id."', '".$_SESSION['store_id']."')";
$result = $db->query($query) or die($db->error);
return $db->insert_id;
}//add log ends here.
function add_receiving($date, $method, $ref_no, $memo, $amount, $client_id) {
global $db;
$query = "INSERT into receivings(receiving_id, datetime, method, ref_no, memo, amount, client_id, agent_id, store_id) VALUES(NULL, '".$date."', '".$method."', '".$ref_no."', '".$memo."', '".$amount."', '".$client_id."', '".$_SESSION['user_id']."', '".$_SESSION['store_id']."')";
$result = $db->query($query) or die($db->error);
return $db->insert_id;
}//add_payment ends here.
function add_return_payment($date, $method, $ref_no, $memo, $amount, $client_id) {
global $db;
$query = "INSERT into sale_return_payment(return_payment_id, datetime, method, ref_no, memo, amount, client_id, agent_id, store_id) VALUES(NULL, '".$date."', '".$method."', '".$ref_no."', '".$memo."', '".$amount."', '".$client_id."', '".$_SESSION['user_id']."', '".$_SESSION['store_id']."')";
$result = $db->query($query) or die($db->error);
return $db->insert_id;
}//add_payment ends here.
function get_client_balance($client_id) {
global $db;
$creditQuery = "SELECt * from creditors WHERE client_id='".$client_id."' AND store_id='".$_SESSION['store_id']."'";
$creditResult = $db->query($creditQuery) or die($db->error);
$receiveable = 0;
while($creditRow = $creditResult->fetch_array()) {
$receiveable += $creditRow['receiveable'];
if($creditRow['receiveable'] == 0) {
$receiveable -= $creditRow['received'];
}
}
$receivingQuery = "SELECt * from receivings WHERE client_id='".$client_id."' AND store_id='".$_SESSION['store_id']."'";
$receivingResult = $db->query($receivingQuery) or die($db->error);
while($recevingRow = $receivingResult->fetch_array()) {
$receiveable -= $recevingRow['amount'];
}
$sale_return_payment = "SELECt * from sale_return_payment WHERE client_id='".$client_id."' AND store_id='".$_SESSION['store_id']."'";
$sale_payment_result = $db->query($sale_return_payment) or die($db->error);
while($sale_return_row = $sale_payment_result->fetch_array()) {
$receiveable -= $sale_return_row['amount'];
}
return $receiveable;
}//get vendor balance ends here.
function list_receivings() {
global $db;
$query = 'SELECT * from receivings WHERE store_id="'.$_SESSION['store_id'].'" ORDER by receiving_id DESC';
$result = $db->query($query) or die($db->error);
$content = '';
while($row = $result->fetch_array()) {
extract($row);
$datetime = strtotime($datetime);
$date = date('d-M-Y', $datetime);
$client = $this->get_client_info($client_id, 'full_name');
$user = new Users;
$agent = $user->get_user_info($agent_id, 'first_name').' '.$user->get_user_info($agent_id, 'last_name');
$content .= '<tr><td>';
$content .= $receiving_id;
$content .= '</td><td>';
$content .= $date;
$content .= '</td><td>';
$content .= $method;
$content .= '</td><td>';
$content .= $ref_no;
$content .= '</td><td>';
$content .= $agent;
$content .= '</td><td>';
$content .= $client;
$content .= '</td><td>';
$content .= $memo;
$content .= '</td><td>';
$content .= $amount;
$content .= '</td>';
if(partial_access('admin')) {
$content .= '<td><form method="post" name="delete" onsubmit="return confirm_delete();" action="">';
$content .= '<input type="hidden" name="delete_receiving" value="'.$receiving_id.'">';
$content .= '<input type="submit" class="btn btn-default btn-sm" value="Delete">';
$content .= '</form>';
$content .= '</td>'; }
$content .= '</tr>';
unset($class);
}//loop ends here.
echo $content;
}//list_notes ends here.
function delete_receiving($receiving_id) {
global $db;
$query = "DELETE from receivings WHERE receiving_id='".$receiving_id."'";
$result = $db->query($query) or die($db->error);
$query = "DELETE from customer_log WHERE transaction_type='Sale Receiving' AND type_table_id='".$receiving_id."'";
$result = $db->query($query) or die($db->error);
$query = "DELETE from customer_log WHERE transaction_type='Receiving' AND type_table_id='".$receiving_id."'";
$result = $db->query($query) or die($db->error);
return 'Receiving deleted Successfuly.';
}//delete_purchase return receiving.
function list_return_payments() {
global $db;
$query = 'SELECT * from sale_return_payment WHERE store_id="'.$_SESSION['store_id'].'" ORDER by return_payment_id DESC';
$result = $db->query($query) or die($db->error);
$content = '';
while($row = $result->fetch_array()) {
extract($row);
$datetime = strtotime($datetime);
$date = date('d-M-Y', $datetime);
$client = $this->get_client_info($client_id, 'full_name');
$user = new Users;
$agent = $user->get_user_info($agent_id, 'first_name').' '.$user->get_user_info($agent_id, 'last_name');
$content .= '<tr><td>';
$content .= $return_payment_id;
$content .= '</td><td>';
$content .= $date;
$content .= '</td><td>';
$content .= $method;
$content .= '</td><td>';
$content .= $ref_no;
$content .= '</td><td>';
$content .= $agent;
$content .= '</td><td>';
$content .= $client;
$content .= '</td><td>';
$content .= $memo;
$content .= '</td><td>';
$content .= $amount;
$content .= '</td>';
if(partial_access('admin')) {
$content .= '<td><form method="post" name="delete" onsubmit="return confirm_delete();" action="">';
$content .= '<input type="hidden" name="delete_sale_return_payment" value="'.$return_payment_id.'">';
$content .= '<input type="submit" class="btn btn-default btn-sm" value="Delete">';
$content .= '</form>';
$content .= '</td>'; }
$content .= '</tr>';
}//loop ends here.
echo $content;
}//list_notes ends here.
function delete_sale_return_payment($return_payment_id) {
global $db;
$query = "DELETE from sale_return_payment WHERE return_payment_id='".$return_payment_id."'";
$result = $db->query($query) or die($db->error);
$query = "DELETE from customer_log WHERE transaction_type='Sale Return Refund' AND type_table_id='".$return_payment_id."'";
$result = $db->query($query) or die($db->error);
return 'Return Payment deleted Successfuly.';
}//delete_purchase return receiving.
function clear_creditors($amount, $client_id){
global $db;
$query = "SELECT * FROM creditors WHERE client_id='".$client_id."' ORDER by credit_id ASC";
$result = $db->query($query) or die($db->error);
while($row = $result->fetch_array()) {
extract($row);
if($receiveable == 0 || $receiveable == $received || $amount == 0) {
//do nothing.
} else {
if($received == 0) {
if($amount < $receiveable) {
$receive = $amount;
} else {
$receive = $receiveable;
}
$query_up = "UPDATE creditors SET
received = '".$receive."'
WHERE credit_id='".$credit_id."'
";
$amount -= $receive;
} else if($received != 0) {
$difference = $receiveable-$received;
if($amount < $difference) {
$receive = $amount+$received;
} else {
$receive = $difference+$received;
}
$query_up = "UPDATE creditors SET
received = '".$receive."'
WHERE credit_id='".$credit_id."'
";
$amount -= $difference;
}
$result_up = $db->query($query_up) or die($db->error);
}//main if ends here.
}//main loop ends.
}//debts clear ends here.--
function customers_balance_summary() {
global $db;
$query = "SELECT * FROM clients WHERE store_id='".$_SESSION['store_id']."' ORDER by full_name ASC";
$result = $db->query($query) or die($db->error);
$content = '';
$grand_total = 0;
while($row = $result->fetch_array()) {
extract($row);
//getting balance.
$balance = $this->get_client_balance($client_id);
$grand_total += $balance;
$content .= '<tr><td>';
$content .= $full_name;
$content .= '</td><td>';
$content .= $business_title;
$content .= '</td><td align="right">';
$content .= currency_format($grand_total);
$content .= '</td></tr>';
}
$new_store = new Store;
$currency = $new_store->get_store_info($_SESSION['store_id'], 'currency');
$content .= '<tr><th colspan="2" align="right">Grand Total</th><th align="right">'.$currency.' '.currency_format($grand_total).'</tH></tr>';
echo $content;
}//customers balance summary ends here.
function customer_ledger_summary($client) {
global $db;
$query = "SELECT * from customer_log WHERE client_id='".$client."' ORDER by customer_log_id ASC";
$result = $db->query($query) or die($db->error);
$balance = 0;
$content = '';
$balance = 0;
while($row = $result->fetch_array()) {
extract($row);
$datetime = strtotime($datetime);
$date = date('d-M-Y', $datetime);
$content .= '<tr><td>';
$content .= $transaction_type;
$content .= '</td><td>';
$content .= $date;
$content .= '</td><td>';
$content .= $type_table_id;
$content .= '</td><td>';
if($transaction_type == 'Sale Invoice' || $transaction_type == 'Cash Sale') {
//Invoice Details.
$sale_query = "SELECT * from sales WHERE sale_id='".$type_table_id."'";
$sale_result = $db->query($sale_query) or die($db->error);
while($sale_row = $sale_result->fetch_array()) {
$content .= $sale_row['memo'];
$content .= '</td><td>';
}
$sale_detail_query = "SELECT * from sale_detail WHERE sale_id='".$type_table_id."'";
$sale_detail_result = $db->query($sale_detail_query) or die($db->error);
$invoice_total = 0;
while($sale_detail_row = $sale_detail_result->fetch_array()) {
$credit_query = "SELECT * from creditors WHERE credit_id='".$sale_detail_row['credit_id']."'";
$credit_result = $db->query($credit_query) or die($db->error);
while($credit_row = $credit_result->fetch_array()) {
$invoice_total += $credit_row['receiveable'];
}
}
$balance = $invoice_total+$balance;
$content .= currency_format($invoice_total);
$content .= '</td><td>';
$content .= currency_format($balance);
$content .= '</td></tr>';
} else if($transaction_type == 'Sale Receiving' || $transaction_type == 'Receiving') {
//Cash receivign.
$receiving_query = "SELECT * from receivings WHERE receiving_id='".$type_table_id."'";
$receiving_result = $db->query($receiving_query) or die($db->error);
while($receiving_row = $receiving_result->fetch_array()) {
$content .= $receiving_row['memo'];
$content .= '</td><td>';
$balance = $balance-$receiving_row['amount'];
$content .= '('.currency_format($receiving_row['amount']).')';
$content .= '</td><td>';
$content .= currency_format($balance);
$content .= '</td></tr>';
}
} else if($transaction_type == 'Invoice Return' || $transaction_type == 'Sale Return') {
//sale return invoice.
$sale_query = "SELECT * from sale_returns WHERE sale_rt_id='".$type_table_id."'";
$sale_result = $db->query($sale_query) or die($db->error);
while($sale_row = $sale_result->fetch_array()) {
$content .= $sale_row['memo'];
$content .= '</td><td>';
}
$sale_detail_query = "SELECT * from sale_return_detail WHERE sale_rt_id='".$type_table_id."'";
$sale_detail_result = $db->query($sale_detail_query) or die($db->error);
$invoice_total = 0;
while($sale_detail_row = $sale_detail_result->fetch_array()) {
$credit_query = "SELECT * from creditors WHERE credit_id='".$sale_detail_row['credit_id']."'";
$credit_result = $db->query($credit_query) or die($db->error);
while($credit_row = $credit_result->fetch_array()) {
$invoice_total += $credit_row['received'];
}
}
$balance = $balance-$invoice_total;
$content .= '('.currency_format($invoice_total).')';
$content .= '</td><td>';
$content .= currency_format($balance);
$content .= '</td></tr>';
} else if($transaction_type == 'Sale Return Refund') {
//sale Return Payment.
$receiving_query = "SELECT * from sale_return_payment WHERE return_payment_id='".$type_table_id."'";
$receiving_result = $db->query($receiving_query) or die($db->error);
while($receiving_row = $receiving_result->fetch_array()) {
$content .= $receiving_row['memo'];
$content .= '</td><td>';
$balance = $balance+$receiving_row['amount'];
$content .= currency_format($receiving_row['amount']);
$content .= '</td><td>';
$content .= currency_format($balance);
$content .= '</td></tr>';
}
}
}//main loop ends here.
echo $content;
}//customer ledger summary ends here.
}//class ends here.
The shown screen code where this class functions are being used:
`
<?php
include('system_load.php');
//This loads system.
//user Authentication.
authenticate_user('subscriber');
//creating company object.
if(partial_access('admin') || $store_access->have_module_access('sales')) {} else {
HEADER('LOCATION: store.php?message=products');
}
if(!isset($_SESSION['store_id']) || $_SESSION['store_id'] == '') {
HEADER('LOCATION: stores.php?message=1');
} //select company redirect ends here.
if(isset($_POST['edit_purchase'])){ $page_title = 'Edit Sale'; } else { $page_title = 'Add Sale';}; //You can edit this to change your page title.
require_once("includes/header.php"); //including header file.
?>
<?php if(isset($_GET['sale_id'])) { ?>
<script type="text/javascript">
window.open('reports/view_sale_invoice.php?sale_id=<?php echo $_GET['sale_id']; ?>', '_blank');
</script>
<?php } ?>
<?php
//display message if exist.
if(isset($_GET['message']) && $_GET['message'] != '') {
echo '<div class="alert alert-success">';
echo $_GET['message'];
echo '</div>';
}
if(isset($message) && $message != '') {
echo '<div class="alert alert-success">';
echo $message;
echo '</div>';
}
?>
<style type="text/css">
textarea:hover, textarea:focus, #items td.total-value textarea:hover, #items td.total-value textarea:focus, .delme:hover { background-color:#EEFF88; }
#items input[type=text] {width:60px;border:0px;}
.delete-wpr { position: relative; }
.delme { display: block; color: #000; text-decoration: none; position: absolute; background: #EEEEEE; font-weight: bold; padding: 0px 3px; border: 1px solid; top: -6px; left: -22px; font-family: Verdana; font-size: 12px; }
</style>
<script type="text/javascript">
jQuery(function($) {
$('form[data-async]').on('submit', function(event) {
var $form = $(this);
var $target = $($form.attr('data-target'));
$.ajax({
type: $form.attr('method'),
url: 'includes/otherprocesses.php',
data: $form.serialize(),
dataType: 'json',
success: function(response) {
var message = response.message;
var client_options = response.client_options;
var client_id = response.client_id;
$('#client_id').html(client_options);
$("#client_id").select2().select2('val', client_id);
$('#success_message').html('<div class="alert alert-success">'+message+'</div>');
}
});
event.preventDefault();
});
});
</script>
<!-- Add new vendor modal starts here. -->
<div class="modal fade" id="addnewclient" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Add new client</h4>
</div>
<div class="modal-body">
<form data-async data-target="#addnewclient" method="POST" enctype="multipart/form-data" role="form">
<div id="success_message"></div>
<table style="width:100%;">
<tr>
<td>
<div class="form-group">
<label class="control-label">Full Name*</label>
<input type="text" class="form-control" name="full_name" placeholder="Client full name" value="" required="required" />
</div>
</td>
<td>
<div class="form-group">
<label class="control-label">Business Title</label>
<input type="hidden" name="add_client" value="1" />
<input type="submit" id="submit" class="btn btn-primary" value="Add client">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!--add new vendor modal ends here.-->
<form action="includes/process_sale.php" method="post">
<div class="row">
<div class="col-sm-5">
<table border="0" cellpadding="5">
<tr>
<td width="110">Date</td>
<td width="300"><input type="text" name="date" class="form-control datepick" readonly="readonly" value="<?php echo date('Y-m-d'); ?>" /></td>
</tr>
<tr>
<td>Custom Inv#</td>
<td><input type="text" placeholder="Custom Invoice number" name="custom_inv_no" class="form-control" /></td>
</tr>
<tr>
<td>Memo</td>
<td><textarea placeholder="Memo" name="memo" class="form-control"></textarea></td>
</tr>
<tr>
<th>Select Client</th>
<td>
<select name="client_id" id="client_id" class="autofill" style="width:100%">
<option value="">Select Client by full name or mobile</option>
<?
=$client->client_options($client->client_id);
?>
</select>
</td>
</tr>
<tr>
<td> </td>
<td><a class="btn btn-default btn-xs" data-toggle="modal" href="#addnewclient">Add new Client</a></td>
</tr>
</table>
</div><!--left-side-form ends here.-->
<script type="text/javascript">
function update_total() {
var grand_total = 0;
i = 1;
$('.total').each(function(i) {
var total = $(this).html();
total = parseFloat(total);
grand_total = total+grand_total;
});
$('#grand_total').html(grand_total.toFixed(2));
}//Update total function ends here.
<?php
require_once("includes/footer.php");
?>
What plattform do you use for the localhost? Online linux server and local a Windows machine? As it is run on the localhost, do you get warnings, notices or the sort? Or even a fatal?
<?
=$client->client_options($client->client_id);
?>
That looks odd. Why the '='?
Okay I finally figured how to make it work by the hint provided above. Actually this Syntax doesn't work in this case:
<?=$client->client_options($client->client_id);?>
The Solution is:
<?php echo $client->client_options($client->client_id); ?>
Thanks all anyway for brainstorming.

How to add a "href" link in a td of data table to open a PHP page

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>";

Categories