Tabledit Datepicker and Simple validation - php

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

Related

PHP/Ajax page navigation url change

Ik want to build a ajax/jquery page navigation so when the user clicks on a page, the url changes to so that there are no problems with browser's back button. I found a lot of answers for this but not what I searched for. I saw this code below on a tutorial site and I want to customize it so that the url moves to. Do I have to build that in the ajax script of on the PHP side? How can I achieve this?
My index.php
<html>
<head>
<title>Webslesson Tutorial | Make Pagination using Jquery, PHP, Ajax and MySQL</title>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<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" />
</head>
<body>
<br /><br />
<div class="container">
<h3 align="center">Make Pagination using Jquery, PHP, Ajax and MySQL</h3><br />
<div class="table-responsive" id="pagination_data">
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
load_data();
function load_data(page)
{
$.ajax({
url:"pagina.php",
method:"POST",
data:{page:page},
success:function(data){
$('#pagination_data').html(data);
history.pushState({ foo: 'bar' }, '', '/bank'); // I tried this line but it don't work
}
})
}
$(document).on('click', '.pagination_link', function(){
var page = $(this).attr("id");
load_data(page);
});
});
</script>
And my pagina.php
<?PHP
$connect = mysqli_connect("hidden", "hidden", "hidden","publiek2") or die("Connection failed: " . mysqli_connect_error());
$record_per_page = 50;
$page = '';
$output = '';
if(isset($_POST["page"]))
{
$page = $_POST["page"];
}
else
{
$page = 1;
}
$start_from = ($page - 1)*$record_per_page;
$query = "SELECT * FROM voertuigen WHERE merk='Chevrolet' AND voorpagina='1' ORDER BY model ASC LIMIT $start_from, $record_per_page";
$result = mysqli_query($connect, $query);
$output .= "
<table class='table table-bordered'>
<tr>
<th width='50%'>Name</th>
<th width='50%'>Phone</th>
</tr>
";
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["merk"].'</td>
<td>'.$row["model"].'</td>
</tr>
';
}
$output .= '</table><br /><div align="center">';
$page_query = "SELECT * FROM voertuigen WHERE merk='Chevrolet' AND voorpagina='1' ORDER BY model ASC";
$page_result = mysqli_query($connect, $page_query);
$total_records = mysqli_num_rows($page_result);
$total_pages = ceil($total_records/$record_per_page);
for($i=1; $i<=$total_pages; $i++)
{
$output .= "<span class='pagination_link' style='cursor:pointer; padding:6px; border:1px solid #ccc;' id='".$i."'>".$i."</span>";
}
$output .= '</div><br /><br />';
echo $output;
?>
Thanks in advance.
I've tried to customize the ajax script.
As a javascript and PHP developer I don't understand much about Jquery but I think the code describes that there is a div called.pagination_link takes id as page number eg: 1. And makes an HTTP POST request to the PHP side. You can simply do this with a sample example in Javascript.
HTML
<div id="1" classname="pagination_link">1</div>
Javascript
const id = document.querySelector('.pagination_link').getAttribute('id');
fetch('pagina.php', {
method : 'POST',
body : id
})
If you want to send data.
I added a hidden text value with the page number as value and called the id 'idd' and recalled that id on the ajax page. It works good now but if I want to go back with browser button, the url moves to the previous page but the results on the page stays te same. How can I resolve that?
My new index.php JS code
<script>
$(document).ready(function(){
var idd;
load_data();
function load_data(page)
{
$.ajax({
url:"pagina.php",
method:"GET",
data:{page:page},
success:function(data){
$('#pagination_data').html(data);
if (idd === undefined) {
alert("ja");
idd = 1;
alert(idd);
history.pushState({}, '', 'http://localhost:4612/pagina/1');
}
else {
idd = $("#idd").val();
history.pushState({}, '', 'http://localhost:4612/pagina/'+idd);
}
}
})
}
$(document).on('click', '.pagination_link', function(){
var page = $(this).attr("id");
load_data(page);
});
});
</script>
and my altered pagina.php
<?PHP
$connect = mysqli_connect("hidden", "hidden", "hidden","publiek2") or die("Connection failed: " . mysqli_connect_error());
$record_per_page = 50;
$page = '';
$output = '';
if(isset($_GET["page"]))
{
$page = $_GET["page"];
echo "<input type='hidden' id='idd' value='".$_GET['page']."'>";
}
else
{
$page = 1;
$idd = 1;
}
$start_from = ($page - 1)*$record_per_page;
$query = "SELECT * FROM voertuigen WHERE merk='Chevrolet' AND voorpagina='1' ORDER BY model ASC LIMIT $start_from, $record_per_page";
$result = mysqli_query($connect, $query);
$output .= "
<table class='table table-bordered'>
<tr>
<th width='50%'>Name</th>
<th width='50%'>Phone</th>
</tr>
";
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["merk"].'</td>
<td>'.$row["model"].'</td>
</tr>
';
}
$output .= '</table><br /><div align="center">';
$page_query = "SELECT * FROM voertuigen WHERE merk='Chevrolet' AND voorpagina='1' ORDER BY model ASC";
$page_result = mysqli_query($connect, $page_query);
$total_records = mysqli_num_rows($page_result);
$total_pages = ceil($total_records/$record_per_page);
for($i=1; $i<=$total_pages; $i++)
{
$output .= "<span class='pagination_link' style='cursor:pointer; padding:6px; border:1px solid #ccc;' id='".$i."'>".$i."</span>";
}
$output .= '</div><br /><br />';
echo $output;
?>

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

server side load script for datatable

I have a database table with a large amount of data, and it takes a lot of time to load into the datatable. So I use the server side script for load data for the current page only.
But now I need to add a new condition in 'where' section and when I add the condition, the search property of datatable not working.
I also need to sort the table by language_id it doesn't work at all
my code is
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Datatable with mysql</title>
<link rel="stylesheet" id="font-awesome-style-css" href="http://phpflow.com/code/css/bootstrap3.min.css" type="text/css" media="all">
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css"/>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
</head>
<body>
<div class="container">
<div class="">
<h1>Data Table</h1>
<div class="">
<table id="employee_grid" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>Empid</th>
<th>Name</th>
<th>Salary</th>
<th>Age</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Empid</th>
<th>Name</th>
<th>Salary</th>
<th>Age</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
<script type="text/javascript">
$( document ).ready(function() {
$('#employee_grid').DataTable({
"bProcessing": true,
"serverSide": true,
"ajax":{
url :"response.php", // json datasource
type: "post", // type of method ,GET/POST/DELETE
error: function(){
$("#employee_grid_processing").css("display","none");
}
}
});
});
</script>
</body>
</html>
response.php
<?php
//include connection file
include_once("connection.php");
// initilize all variable
$params = $columns = $totalRecords = $data = array();
$params = $_REQUEST;
//define index of column
$columns = array(
0 =>'blog_id',
1 =>'blog_caption',
2 => 'publisher_name',
3 => 'published_date'
);
$where = $sqlTot = $sqlRec = "";
// check search value exist
if( !empty($params['search']['value']) ) {
$where .=" WHERE ";
$where .=" ( blog_caption LIKE '".$params['search']['value']."%' ";
$where .=" OR publisher_name LIKE '".$params['search']['value']."%' ";
$where .=" OR published_date LIKE '".$params['search']['value']."%' )";
}
// getting total number records without any search
$sql = "SELECT blog_id,blog_caption,publisher_name,published_date FROM `blog_table` ";
$sqlTot .= $sql;
$sqlRec .= $sql;
//concatenate search sql if value exist
if(isset($where) && $where != '') {
$sqlTot .= $where;
$sqlRec .= $where;
}
$sqlRec .= " ORDER BY ". $columns[$params['order'][0]['column']]." ".$params['order'][0]['dir']." LIMIT ".$params['start']." ,".$params['length']." ";
$queryTot = mysqli_query($conn, $sqlTot) or die("database error:". mysqli_error($conn));
$totalRecords = mysqli_num_rows($queryTot);
$queryRecords = mysqli_query($conn, $sqlRec) or die("error to fetch employees data");
//iterate on results row and create new index array of data
while( $row = mysqli_fetch_row($queryRecords) ) {
$data[] = $row;
}
$json_data = array(
"draw" => intval( $params['draw'] ),
"recordsTotal" => intval( $totalRecords ),
"recordsFiltered" => intval($totalRecords),
"data" => $data // total data array
);
echo json_encode($json_data); // send data as json format
?>
Thanks in advance.

datatable plugin php and json errror

i am new to programming.i try to design a admin panel that can directly edit the users data with the help of datatable plugin.this there is some error with JSON format
this is my index page
<html>
<head>
<title>Live Add Edit Delete Datatables Records using PHP Ajax</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>
<style>
body
{
margin:0;
padding:0;
background-color:#f1f1f1;
}
.box
{
width:1270px;
padding:20px;
background-color:#fff;
border:1px solid #ccc;
border-radius:5px;
margin-top:25px;
box-sizing:border-box;
}
</style>
</head>
<body>
<div class="container box">
<h1 align="center">Live Add Edit Delete Datatables Records using PHP Ajax</h1>
<br />
<div class="table-responsive">
<br />
<div align="right">
<button type="button" name="add" id="add" class="btn btn-info">Add</button>
</div>
<br />
<div id="alert_message"></div>
<table id="user_data" class="table table-bordered table-striped">
<thead>
<tr>
<th>Staff id</th>
<th>Password</th>
<th>Email_id</th>
<th>gender</th>
<th>qualification</th>
<th>course1</th>
<th>course2</th>
<th>course3</th>
<th></th>
</tr>
</thead>
</table>
</div>
</div>
</body>
</html>
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
fetch_data();
function fetch_data()
{
var dataTable = $('#user_data').DataTable({
"processing" : true,
"serverSide" : true,
"order" : [],
"ajax" : {
url:"fetch.php",
type:"POST"
}
});
}
function update_data(id, column_name, value)
{
$.ajax({
url:"update.php",
method:"POST",
data:{id:id, column_name:column_name, value:value},
success:function(data)
{
$('#alert_message').html('<div class="alert alert-success">'+data+'</div>');
$('#user_data').DataTable().destroy();
fetch_data();
}
});
setInterval(function(){
$('#alert_message').html('');
}, 5000);
}
$(document).on('blur', '.update', function(){
var id = $(this).data("id");
var column_name = $(this).data("column");
var value = $(this).text();
update_data(id, column_name, value);
});
$('#add').click(function(){
var html = '<tr>';
html += '<td contenteditable id="data1"></td>';
html += '<td contenteditable id="data2"></td>';
html += '<td contenteditable id="data3"></td>';
html += '<td><button type="button" name="insert" id="insert" class="btn btn-success btn-xs">Insert</button></td>';
html += '</tr>';
$('#user_data tbody').prepend(html);
});
$(document).on('click', '#insert', function(){
var first_name = $('#data1').text();
var last_name = $('#data2').text();
var password = $('#data3').text();
if(first_name != '' && last_name != '' && password != '')
{
$.ajax({
url:"insert.php",
method:"POST",
data:{first_name:first_name, last_name:last_name, password:password},
success:function(data)
{
$('#alert_message').html('<div class="alert alert-success">'+data+'</div>');
$('#user_data').DataTable().destroy();
fetch_data();
}
});
setInterval(function(){
$('#alert_message').html('');
}, 5000);
}
else
{
alert("Both Fields is required");
}
});
$(document).on('click', '.delete', function(){
var id = $(this).attr("id");
if(confirm("Are you sure you want to remove this?"))
{
$.ajax({
url:"delete.php",
method:"POST",
data:{id:id},
success:function(data){
$('#alert_message').html('<div class="alert alert-success">'+data+'</div>');
$('#user_data').DataTable().destroy();
fetch_data();
}
});
setInterval(function(){
$('#alert_message').html('');
}, 5000);
}
});
});
</script>
This is my fetch.php file
<?php
//fetch.php
$connect = mysqli_connect("localhost", "root", "", "flash");
$columns = array('staff_id', 'password','email_id','gender','qualification','course1','course2','course3');
$query = "SELECT * FROM staff ";
if(isset($_POST["search"]["value"]))
{
$query .= '
WHERE staff_id LIKE "%'.$_POST["search"]["value"].'%"
OR email_id LIKE "%'.$_POST["search"]["value"].'%"
';
}
if(isset($_POST["order"]))
{
$query .= 'ORDER BY '.$columns[$_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'];
}
$number_filter_row = mysqli_num_rows(mysqli_query($connect, $query));
$result = mysqli_query($connect, $query . $query1);
$data = array();
while($row = mysqli_fetch_array($result))
{
$sub_array = array();
$sub_array[] = '<div contenteditable class="update" data-id="'.$row["SINO"].'" data-column="staff_id">' . $row["staff_id"] . '</div>';
$sub_array[] = '<div contenteditable class="update" data-id="'.$row["SINO"].'" data-column="password">' . $row["password"] . '</div>';
$sub_array[] = '<div contenteditable class="update" data-id="'.$row["SINO"].'" data-column="email_id">' . $row["email_id"] . '</div>';
$sub_array[] = '<div contenteditable class="update" data-id="'.$row["SINO"].'" data-column="gender">' . $row["gender"] . '</div>';
$sub_array[] = '<div contenteditable class="update" data-id="'.$row["SINO"].'" data-column="qualification">' . $row["qualification"] . '</div>';
$sub_array[] = '<div contenteditable class="update" data-id="'.$row["SINO"].'" data-column="course1">' . $row["course1"] . '</div>';
$sub_array[] = '<div contenteditable class="update" data-id="'.$row["SINO"].'" data-column="course2">' . $row["course2"] . '</div>';
$sub_array[] = '<div contenteditable class="update" data-id="'.$row["SINO"].'" data-column="course3">' . $row["course3"] . '</div>';
$sub_array[] = '<button type="button" name="delete" class="btn btn-danger btn-xs delete" id="'.$row["SINO"].'">Delete</button>';
$data[] = $sub_array;
}
function get_all_data($connect)
{
$query = "SELECT * FROM staff";
$result = mysqli_query($connect, $query);
return mysqli_num_rows($result);
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => get_all_data($connect),
"recordsFiltered" => $number_filter_row,
"data" => $data
);
echo json_encode($output);
?>
this shows an alert message like
DataTables warning: table id=user_data - Invalid JSON response. For
more information about this error, please see
http://datatables.net/tn/1
the fetch.php file shows a error statement like
Notice: Undefined index: length in C:\xampp\htdocs\FLASH\admin
modify\fetch.php on line 28
Notice: Undefined index: start in C:\xampp\htdocs\FLASH\admin
modify\fetch.php on line 30
Notice: Undefined index: length in C:\xampp\htdocs\FLASH\admin
modify\fetch.php on line 30
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result,
boolean given in C:\xampp\htdocs\FLASH\admin modify\fetch.php on line
33
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result,
boolean given in C:\xampp\htdocs\FLASH\admin modify\fetch.php on line
39
Notice: Undefined index: draw in C:\xampp\htdocs\FLASH\admin
modify\fetch.php on line 62
{"draw":0,"recordsTotal":4,"recordsFiltered":null,"data":[]}
guy please help me to solve this issue please.

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