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?
Related
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 ";
I have datatables contain input box and button for each row data, for sure form was added outside table tag, but i have issue while clicking on button submit inside that table, the button did not work well and no appear anything error logs
My Controller.php for displaying row:
public function tagihankost()
{
$list = $this->tagihan->get_datatables();
$data = array();
foreach ($list as $tagih) {
$row = array();
$format = number_format($tagih->harga, '0', '', '.');
$row[] = "<input type='text' value='$tagih->bulan' id='bulan' class='rowtagihan' form='payment-form' readonly>";
$row[] = "<input type='number' value='$format' id='harga' class='rowtagihan' form='payment-form' readonly>";
if ($tagih->status == 200) {
$row[] = "<span class='badge bg-success' style='color:white'>Lunas</span>";
} elseif ($tagih->status == 201) {
$row[] = "<span class='badge bg-warning' style='color:black'>Pending</span>";
} else {
$row[] = "<span class='badge bg-danger' style='color:white'>Belum Bayar</span>";
};
$row[] = "<button id='pay-button'>Pay!</button>";
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->tagihan->count_all(),
"recordsFiltered" => $this->tagihan->count_filtered(),
"data" => $data,
);
echo json_encode($output);
}
My View.php :
<div class="card bodycontent">
<div class="card-body">
<div class="tab-pane table-responsive">
<table id="tablekost" class="table table-striped table-bordered" width="100%" cellspacing="0">
<thead>
<tr>
<td>Bulan</td>
<td>Tagihan</td>
<td>Status</td>
<td>#</td>
</tr>
</thead>
<form id="payment-form" method="post" action="<?= site_url() ?>/snap/finish">
<input type="hidden" name="result_type" id="result-type" value="">
<input type="hidden" name="result_data" id="result-data" value="">
</form>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
And the last thing is my JS:
<script type="text/javascript">
$('#pay-button').click(function(event) {
event.preventDefault();
$(this).attr("disabled", "disabled");
$.ajax({
url: '<?= site_url() ?>/snap/token',
cache: false,
success: function(data) {
//location = data;
console.log('token = ' + data);
var resultType = document.getElementById('result-type');
var resultData = document.getElementById('result-data');
function changeResult(type, data) {
$("#result-type").val(type);
$("#result-data").val(JSON.stringify(data));
//resultType.innerHTML = type;
//resultData.innerHTML = JSON.stringify(data);
}
snap.pay(data, {
onSuccess: function(result) {
changeResult('success', result);
console.log(result.status_message);
console.log(result);
$("#payment-form").submit();
},
onPending: function(result) {
changeResult('pending', result);
console.log(result.status_message);
$("#payment-form").submit();
},
onError: function(result) {
changeResult('error', result);
console.log(result.status_message);
$("#payment-form").submit();
}
});
}
});
});
So what i have missed?
hey guys I need some help please guide me where I am doing wrong in coding. This is table of showing record of users
I want pagination operation and search operation on my index.php file. Pagination is working but when I am type a single letter (example: a or Haris) on search bar then show me message that data not found this is message showing when type a username on search bar
This my ajax function that on index.php file I am pagination or search
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"search.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#message').keyup(function(){
var srch = $(this).val();
if(srch != '')
{
load_data(srch);
}
else
{
load_data();
}
});
function load_data(page)
{
$.ajax({
url:"search.php",
method:"GET",
data:{page:page},
success:function(data){
$('#pagination_data').html(data);
}
})
}
$(document).on('click', '.pagination_link', function(){
var page = $(this).attr("id");
load_data(page);
});
});
</script>
This my search.php file
<?php
include("common/config.php");
$output = '';
if(isset($_POST["query"]))
{
$search = $_POST["query"];
$where = "id LIKE '%".$search."%'
OR name LIKE '%".$search."%'
OR email LIKE '%".$search."%'
OR phone LIKE '%".$search."%'";
$query = $db->select(array("*"),"user","$where","","id desc","");
}
else
{
$limit = 5;
$page = '';
if (isset($_GET["page"] ))
{
$page = $_GET["page"];
}
else
{
$page=1;
}
$record_index= ($page-1) * $limit;
$query = $db->select(array("*"),PREFIX."user", "", "", "id desc", "$record_index, $limit");
}
if($query)
{
$output .= '
<div class="table-responsive">
<table class="table table bordered">
<tr>
<th style="text-align: center !important;"><input type="checkbox" name="select_all" id="select_all" value=""/></th>
<th style="text-align: center !important;">ID</th>
<th style="text-align: center !important;">Name</th>
<th style="text-align: center !important;">Email</th>
<th style="text-align: center !important;">Phone</th>
<th colspan="4" style="text-align: center !important;">Action</th>
</tr>
';
foreach($query as $row)
{
$output .= '
<tr align="center">
<td align="center"><input type="checkbox" name="checked_id[]"
class="checkbox" value="'.$row->id.'"/></td>
<td>'.$row->id.'</td>
<td>'.$row->name.'</td>
<td>'.$row->email.'</td>
<td>'.$row->phone.'</td>
<td>Edit</td>
<td><a onclick="return confirm(\'Are you sure to delete?\')"
href="del.php?del='.$row->id.'">Delete</a></td>
</tr>';
}
$output .= '</table><br /><div align="center">';
$total_pages = ceil($db->countfields("*","user") / $limit);
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;
}
else
{
echo 'Data Not Found';
}
?>
When I am change the name of function,pagination is working but its still search a user record not working.
<script>
$(document).ready(function(){
load_data_1();
load_data_2();
function load_data_1(query)
{
$.ajax({
url:"search.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#message').keyup(function(){
var srch = $(this).val();
if(srch != '')
{
load_data(srch);
}
else
{
load_data_1();
}
});
function load_data_2(page)
{
$.ajax({
url:"search.php",
method:"GET",
data:{page:page},
success:function(data){
$('#pagination_data').html(data);
}
})
}
$(document).on('click', '.pagination_link', function(){
var page = $(this).attr("id");
load_data_2(page);
});
});
</script>
I don't see from your code what "PREFIX" is, but in the search query it is missing while it is present in the pagination query. Hope it helps
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>";
I have four different files
index.php
select.php
insert.php
edit.php
delete.php
In my backend I have created a database named 'ecc'
Database 'ecc' has atable named 'task'
The table task has following fields
id, name, category, cost
Datatype for id set to int and index as primary also id field is on auto increment
My Issue:My code is only displaying 'Live Table Data'.
It would be grate if someone rewrite it or suggest some changes.
index.php
<html>
<head>
<title>Live Table Data Edit</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<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>
</head>
<body>
<div class="container">
<br />
<br />
<br />
<div class="table-responsive">
<h3 align="center">Live Table Add Edit Delete using Ajax Jquery in PHP Mysql</h3><br />
<div id="live_data"></div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
function fetch_data()
{
$.ajax({
url:"select.php",
method:"POST",
success:function(data){
$('#live_data').html(data);
}
});
}
fetch_data();
$(document).on('click', '#btn_add', function(){
var name = $('#name').text();
var category = $('#category').text();
var cost = $('#cost').text();
if(name == '')
{
alert("Enter Service Name");
return false;
}
if(category == '')
{
alert("Enter Category of Service");
return false;
}
if(cost == '')
{
alert("Enter cost");
return false;
}
$.ajax({
url:"insert.php",
method:"POST",
data:{name:name, category:category, cost:cost},
dataType:"text",
success:function(data)
{
alert(data);
fetch_data();
}
})
});
function edit_data(id, text, column_name)
{
$.ajax({
url:"edit.php",
method:"POST",
data:{id:id, text:text, column_name:column_name},
dataType:"text",
success:function(data){
alert(data);
}
});
}
$(document).on('blur', '.name', function(){
var id = $(this).data("id1");
var name = $(this).text();
edit_data(id, name, "name");
});
$(document).on('blur', '.category', function(){
var id = $(this).data("id2");
var category = $(this).text();
edit_data(id,category, "category");
$(document).on('blur', '.cost', function(){
var id = $(this).data("id3");
var category = $(this).text();
edit_data(id,cost, "cost");
});
$(document).on('click', '.btn_delete', function(){
var id=$(this).data("id4");
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
url:"delete.php",
method:"POST",
data:{id:id},
dataType:"text",
success:function(data){
alert(data);
fetch_data();
}
});
}
});
});
</script>
select.php
<?php
$connect = mysqli_connect("localhost", "root", "", "ecc");
$output = '';
$sql = "SELECT * FROM task ORDER BY id DESC";
$result = mysqli_query($connect, $sql);
$output .= '
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="10%">Id</th>
<th width="40%">First Name</th>
<th width="40%">Last Name</th>
<th width="10%">Delete</th>
</tr>';
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["id"].'</td>
<td class="name" data-id1="'.$row["id"].'" contenteditable>'.$row["name"].'</td>
<td class="category" data-id2="'.$row["id"].'" contenteditable>'.$row["category"].'</td>
<td class="cost" data-id3="'.$row["id"].'" contenteditable>'.$row["cost"].'</td>
<td><button type="button" name="delete_btn" data-id4="'.$row["id"].'" class="btn btn-xs btn-danger btn_delete">x</button></td>
</tr>
';
}
$output .= '
<tr>
<td></td>
<td id="name" contenteditable></td>
<td id="category" contenteditable></td>
<td id="cost" contenteditable></td>
<td><button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">+</button></td>
</tr>
';
}
else
{
$output .= '<tr>
<td colspan="4">Data not Found</td>
</tr>';
}
$output .= '</table>
</div>';
echo $output;
?>
insert.php
<?php
$connect = mysqli_connect("localhost", "root", "", "test_db");
$sql = "INSERT INTO tbl_sample(name, category, cost) VALUES('".$_POST["name"]."', '".$_POST["category"]."', '".$_POST["cost"]."')";
if(mysqli_query($connect, $sql))
{
echo 'Data Inserted';
}
?>
edit.php
<?php
$connect = mysqli_connect("localhost", "root", "", "ecc");
$id = $_POST["id"];
$text = $_POST["text"];
$column_name = $_POST["column_name"];
$sql = "UPDATE task SET ".$column_name."='".$text."' WHERE id='".$id."'";
if(mysqli_query($connect, $sql))
{
echo 'Data Updated';
}
?>
delete.php
<?php
$connect = mysqli_connect("localhost", "root", "", "ecc");
$sql = "DELETE FROM task WHERE id = '".$_POST["id"]."'";
if(mysqli_query($connect, $sql))
{
echo 'Data Deleted';
}
?>
you can use data tables for this, no need of all this
https://editor.datatables.net/examples/inline-editing/simple
check this, data tables provide libraries for this