PHP AJAX - Datatable not searching (glitch/error) - php

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

Related

Tabledit Datepicker and Simple validation

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

PHP Ajax update/edit record

Can anyone help me on this. I've been working it about 3 days.
This is about updating the records. When I update the data, all data's updated except for the the "file". The "file" became empty on the database.
Here is the code for;
EDIT/UPDATE FORM:
<label style="color:#e91e63">Attachement</label>
<div class="input-group input-group-md">
<span class="input-group-addon">
<i class="material-icons">file_upload</i>
</span>
<div class="form-line">
<input type="file" name="files" id="files" required>
</div>
</div>
<!-- Edited Date -->
<input type="hidden" name="id" id="id" />
<input type="submit" name="insert" id="insert" value="Insert" class="btn btn-success waves-effect" />
<script>
$(document).ready(function(){
$('#edit').click(function(){
$('#insert').val("Insert");
$('#insert_form')[0].reset();
});
$(document).on('click', '.edit_data', function(){
var id = $(this).attr("id");
var extension = $('#files').val().split('.').pop().toLowerCase();
if(extension != '') {
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg', 'pdf']) == -1) {
alert("Invalid File");
$('#files').val('');
return false;
}
}
$.ajax({
url:"script/fetch.php",
method:"POST",
data:{id:id},
dataType:"json",
success:function(data){
$('#dated').val(data.dated);
$('#ctrl_no').val(data.ctrl_no);
$('#title').val(data.title);
$('#category').val(data.category);
$('#file').val(data.file);
$('#fname').val(data.fname);
$('#adate').val(data.adate);
$('#createdby').val(data.createdby);
$('#id').val(data.id);
$('#insert').val("Update");
$('#update_Modal').modal('show');
}
});
});
$('#insert_form').on("submit", function(event){
event.preventDefault();
$.ajax({
url:"script/insert.php",
method:"POST",
data:$('#insert_form').serialize(),
beforeSend:function(){
$('#insert').val("Inserting");
},
success:function(data){
$('#insert_form')[0].reset();
$('#update_Modal').modal('hide');
$('#refresh').html(data);
}
});
});
});
</script>
Fetching the data from the database:
<?php
//fetch.php
$connect = mysqli_connect("localhost", "root", "", "record");
if(isset($_POST["id"]))
{
$query = "SELECT * FROM dashboard WHERE id = '".$_POST["id"]."'";
$result = mysqli_query($connect, $query);
$row = mysqli_fetch_array($result);
echo json_encode($row);
}
?>
Updating the data.
<?php
$connect = mysqli_connect("localhost", "root", "", "record");
if(!empty($_POST))
{
$output = '';
$message = '';
$ctrl_no = mysqli_real_escape_string($connect, $_POST["ctrl_no"]);
$title = mysqli_real_escape_string($connect, $_POST["title"]);
$category = mysqli_real_escape_string($connect, $_POST["category"]);
$fname = mysqli_real_escape_string($connect, $_POST["fname"]);
$adate = mysqli_real_escape_string($connect, $_POST["adate"]);
$createdby = mysqli_real_escape_string($connect, $_POST["createdby"]);
//file upload
$file = '';
if($_FILES["files"]["name"] = '')
{
$file = upload_file();
}
else
{
$file = $_POST["file"];
}
if($_POST["id"] != '')
{
$query = "
UPDATE `dashboard`
SET
`ctrl_no`='$ctrl_no',
`title`='$title',
`category`='$category',
`file`='$file',
`fname`='$fname',
`adate` = '$adate',
`createdby` = '$createdby'
WHERE `id`='".$_POST["id"]."'";
$message = 'Data Updated.';
}
if(mysqli_query($connect, $query))
{
$output .= "<div class='alert alert-success alert-dismissible'>
<a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a>
<strong>Success!</strong> $message
</div>";
$select_query = "SELECT * FROM `dashboard` ORDER BY `id` DESC";
$result = mysqli_query($connect, $select_query);
$output .= '
<table id="dataTable" style="width:100%" class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th width="6%"><b>Date</b></th>
<th width="8%"><b>Control No.</b></th>
<th width="37%"><b>Title / Particular</b></th>
<th width="17%"><b>Category</b></th>
<th width="10%"><b>From /<br />End-user</b></th>
<th width="10%"><b>File</b></th>
<th width="7%"><b>Action</b></th>
</tr>
</thead>
<tbody>
';
while($row = mysqli_fetch_array($result))
{
$output .= '';
}
$output .= '</tbody></table>';
}
echo $output;
}
function upload_file()
{
if(isset($_FILES["files"]))
{
$extension = explode('.', $_FILES['files']['name']);
$new_name = rand() . '.' . $extension[1];
$destination = '../file/' . $new_name;
move_uploaded_file($_FILES['files']['tmp_name'], $destination);
return $new_name;
}
}
?>
<!-- Alert Success -->
<script>
window.setTimeout(function() {
$(".alert").fadeTo(500, 0).slideUp(500, function(){
$(this).remove();
});
}, 5000); //timeout
</script>
The only problem is the file that I can't update. Any ideas? Help is much appreciated. Thanks.
I think ,you are assigning the name of file via input field.if somebody does not assign the value via input filed ,you have used the method upload_file() .so try to change your if with $_POST["file"] = '' which check whether name is assigned or not ,if assigned the used given else used name define in your upload_file().
<?php
$connect = mysqli_connect("localhost", "root", "", "record");
if(!empty($_POST))
{
$output = '';
$message = '';
$ctrl_no = mysqli_real_escape_string($connect, $_POST["ctrl_no"]);
$title = mysqli_real_escape_string($connect, $_POST["title"]);
$category = mysqli_real_escape_string($connect, $_POST["category"]);
$fname = mysqli_real_escape_string($connect, $_POST["fname"]);
$adate = mysqli_real_escape_string($connect, $_POST["adate"]);
$createdby = mysqli_real_escape_string($connect, $_POST["createdby"]);
//file upload
$file = '';
//make the change here in if
if($_POST["file"] = '')
{
$file = upload_file();
}
else
{
$file = $_POST["file"];
}
if($_POST["id"] != '')
{
$query = "
UPDATE `dashboard`
SET
`ctrl_no`='$ctrl_no',
`title`='$title',
`category`='$category',
`file`='$file',
`fname`='$fname',
`adate` = '$adate',
`createdby` = '$createdby'
WHERE `id`='".$_POST["id"]."'";
$message = 'Data Updated.';
}
if(mysqli_query($connect, $query))
{
$output .= "<div class='alert alert-success alert-dismissible'>
<a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a>
<strong>Success!</strong> $message
</div>";
$select_query = "SELECT * FROM `dashboard` ORDER BY `id` DESC";
$result = mysqli_query($connect, $select_query);
$output .= '
<table id="dataTable" style="width:100%" class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th width="6%"><b>Date</b></th>
<th width="8%"><b>Control No.</b></th>
<th width="37%"><b>Title / Particular</b></th>
<th width="17%"><b>Category</b></th>
<th width="10%"><b>From /<br />End-user</b></th>
<th width="10%"><b>File</b></th>
<th width="7%"><b>Action</b></th>
</tr>
</thead>
<tbody>
';
while($row = mysqli_fetch_array($result))
{
$output .= '';
}
$output .= '</tbody></table>';
}
echo $output;
}
function upload_file()
{
if(isset($_FILES["files"]))
{
$extension = explode('.', $_FILES['files']['name']);
$new_name = rand() . '.' . $extension[1];
$destination = '../file/' . $new_name;
move_uploaded_file($_FILES['files']['tmp_name'], $destination);
return $new_name;
}
}
?>
<!-- Alert Success -->
<script>
window.setTimeout(function() {
$(".alert").fadeTo(500, 0).slideUp(500, function(){
$(this).remove();
});
}, 5000); //timeout
</script>
Are you sure you get file to server side? if not, you want to pass files as this.(this is example Iam sure you will understand how to fit this to your code). key element is formData :)
var formData = new FormData($("#formid")[0]);
$.ajax({
url:'url',
type: 'POST',
data: formData,
processData: false,
contentType: false,
async: false,
success:function(response){
if(response == '100'){
swal({
title: "Blog Added",
text: "Blog Added Successfully",
type: "success",
confirmButtonText: "OK",
showCancelButton: false,
}, function(){
/*location.reload();*/
window.location.href = 'redirect link';
});
}else{
toastr.error(response);
}
}
});
How to pass file data with AJAX and jQuery?

datatable and jquery doesn't working

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

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