CakePHP: Table reordering - php

I want to implement drag and drop reordering functionality with auto save on a cakephp table.
I am trying to implement this example in my CakePHP project without the use of SQL commands.
I want to update the priority fields of the table rows.
So in view.ctp:
<div class="container">
<table class="table table-bordered">
<tr>
<th>#</th>
<th>Name</th>
<th>Defination</th>
</tr>
<tbody class="row_position">
<?php
foreach ($user->tasks_to as $task) {
?>
<tr id="<?php echo $task['id'] ?>">
<td><?php echo $task['id'] ?></td>
<td><?php echo $task['name'] ?></td>
<td><?php echo $task['description'] ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<script type="text/javascript">
$( ".row_position" ).sortable({
delay: 150,
stop: function() {
var selectedData = new Array();
$('.row_position>tr').each(function() {
selectedData.push($(this).attr("id"));
});
updateOrder(selectedData);
}
});
function updateOrder(data) {
$.ajax({
url:"updateTasksOrder",
type:'post',
data:{position:data},
success:function(){
alert('your change successfully saved');
}
})
}
</script>
and in the controller:
public function beforeFilter(Event $event) {
parent::beforeFilter($event);
$this->Auth->allow();
}
public function updateTasksOrder()
{
$this->autoRender = false;
$position = $_POST['position'];
$i=1;
$connection = ConnectionManager::get('default');
foreach($position as $k=>$v){
$connection->update('tasks', ['priority' => $i], ['id' => $v]);
$i++;
}
}
But its not working, it's not updating priority field. Any suggestions why?

Related

Dynamic Drag and Drop table rows

I try to make some reorder with drag and drop with PHP and some ajax with this tutorial.
I set up my files for my needs but nothing going on.
On my index.php just change this thing that equal to my MySQL
$sql = "SELECT * FROM channels ORDER BY channel_number";
$users = $mysqli->query($sql);
while($user = $users->fetch_assoc()){
?>
<tr id="<?php echo $user['id'] ?>">
<td><?php echo $user['channel_number'] ?></td>
<td><?php echo $user['title'] ?></td>
</tr>
<?php } ?>
Here is Java script in index.php:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
</head>
<body>
<script type="text/javascript">
$( ".row_position" ).sortable({
delay: 150,
stop: function() {
var selectedData = new Array();
$('.row_position>tr').each(function() {
selectedData.push($(this).attr("id"));
});
updateOrder(selectedData);
}
});
function updateOrder(data) {
$.ajax({
url:"ajaxPro.php",
type:'post',
data:{position:data},
success:function(){
alert('your change successfully saved');
}
})
}
</script>
</html>
Here is and ajaxPro.php that i change:
require('db_config.php');
$position = $_POST['position'];
$i=1;
foreach($position as $k=>$v){
$sql = "Update `channels` SET `channel_number`=".$i." WHERE `id`=".$v;
$mysqli->query($sql);
$i++;
}
And here is MySQL
When I try to reorder, just want to change field channel_number but nothing goings-on. Where is my mistake
I've change some code, and turn on some log, but still have problem. If anyone can assist will be so happy. Here it is:
index.php
<div class="container">
<h3 class="text-center">Dynamic Drag and Drop table rows in PHP Mysql - ItSolutionStuff.com</h3>
<table id="myTable" class="table table-bordered">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">#</th>
<th scope="col">Name</th>
</tr>
</thead>
<tbody class="row_position">
<?php
require('db_config.php');
$sql = "SELECT * FROM channels ORDER BY channel_number";
$users = $mysqli->query($sql);
while($user = $users->fetch_assoc()){
?>
<tr id="<?php echo $user['id'] ?>"> <!-- data-channel-number="<?php echo $user['channel_number'] ?>">-->
<td><?php echo $user['id'] ?></td>
<td class="index"><?php echo $user['channel_number'] ?></td>
<td><?php echo $user['title'] ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div> <!-- container / end -->
</body>
<!--<script type="text/javascript">
$( ".row_position" ).sortable({
delay: 150,
stop: function() {
//console.log(chArray);
}
});
</script>-->
<script>
var fixHelperModified = function(e, tr) {
var $originals = tr.children();
var $helper = tr.clone();
$helper.children().each(function(index) {
$(this).width($originals.eq(index).width())
});
return $helper;
},
updateIndex = function(e, ui) {
$('td.index', ui.item.parent()).each(function (i) {
$(this).text(i+1);
});
};
$("#myTable tbody").sortable({
distance: 5,
//delay: 100,
opacity: 0.6,
cursor: 'move',
helper: fixHelperModified,
update: function() {
var chArray = [];
$('.row_position>tr').each(function() {
chArray.push({
chid : $(this).attr("id"),
chnumber : $(this).closest('tr').find('td.index').text()
});
});
console.log(chArray);
// console.log(data);
$.ajax({
url:"ajaxPro.php",
type:'post',
data:{position:chArray},
success:function(data){
console.log(data);
//alert('your change successfully saved');
},
error: function (error) {
// console.log(error);
}
})
},
stop: updateIndex
}).disableSelection();
</script>
</html>
ajaxPro.php
error_reporting(1);
require('db_config.php');
$data = $_POST['position'];
echo $data;
//$i=1;
foreach($data as $d){
echo $d['chnumber'];
$sql = "Update channels SET channel_number=".$d['chnumber']." WHERE id=".$d['chid'];
$mysqli->query($sql);
}
It's look good in browser everything is changed (if i move chanel from possition 4 to position 2 it's change on the screen to position 2, but in array chnumber is still 4, and i don't know how to change this.
Here is some pics.
1st order when you load page
Reorder when move channel from pos:4 to pos:2
And here is console log

How to update multple rows checkbox with one button Codeigniter

Hey guys can you guys help me with this checkbox problem? If I check the column and press update, I want the update to happen at current time.
this is an example
I want if I check the checkbox and press the update button and the column will update at the current time
This is my view :
<div class="container">
<div class="row">
<div class="col-md-10">
<div class="panel panel-info">
<div class="panel-heading">Setting Jam & Tanggal Mesin</div>
<div class="panel-body">
<table id="devid_auto" class="table table-bordered dt-responsive" cellspacing="0" width="100%">
<thead>
<tr>
<th width="1%" align="center"><input type="checkbox" onClick="toggle(this)" id="checkAll" name="checkAll" /></th>
<th width="10%" align="center">Nama Mesin</th>
<th width="5%" align="center">IP Address</th>
<th width="10%" align="center">SN</th>
<th width="5%" align="center">Ethernet Port</th>
<th width="10%" align="center">Last Update</th>
</tr>
</thead>
<tbody>
<?php
foreach($data as $d){
?>
<tr>
<td><input class="childbox" type="checkbox" name="msg[]" id="id" value="<?php echo $d['devid_auto'] ?>" /></td>
<td class="data-check" ><?php echo $d['device_name']; ?></td>
<td class="data-check" ><?php echo $d['ip_address']; ?></td>
<td class="data-check" ><?php echo $d['sn']; ?></td>
<td class="data-check" ><?php echo $d['ethernet_port']; ?></td>
<td class="data-check" ><?php echo $d['lastupdate_date']; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
<div class="form-group">
<label for="colFormLabelLg" class="col-sm-3 col-form-label col-form-label-lg">Tanggal & Waktu Sekarang</label>
<div class="col-sm-3">
<input type="" class="form-control" id="" value="<?php date_default_timezone_set("Asia/Jakarta"); echo date(" Y-m-d H:i:s ");?>"" readonly>
</div>
</div>
</div>
<div class="panel-footer text-right">
<button allign="center" class="btn btn-danger" onclick="update()">Update Date and time</button>
</div>
</div>
<script src="<?php echo base_url() ?>assets/baru/jquery-3.2.1.min.js"></script>
<script src="<?php echo base_url() ?>assets/baru/jquery.dataTables.min.js"></script>
<script src="<?php echo base_url() ?>assets/baru/dataTables.bootstrap4.min.js"></script>
<script type="text/javascript">
$(document).ready( function ()
{
$('#devid_auto').DataTable();
$("input[name='checkAll']").click(function() {
var checked = $(this).attr("checked");
$("#devid_auto tr td input:checkbox").attr("checked", checked); });
});
function toggle(id)
{
checkboxes = document.getElementsByName('msg[]');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = id.checked;
}
}
function update(id)
{
var list_id = [];
$("#id:checked").each(function() {
list_id.push(parseInt(this.value));
});
console.info(JSON.stringify(list_id));
if(list_id.length > 0)
{
if(confirm('Are you sure update this '+list_id.length+' data?'))
{
$.ajax({
type: 'POST',
data: {'devid_auto': list_id},
url: '<?php echo site_url('setting/mesin_update')?>',
success: function(result)
{
var hasil = result.replace(/\s/g,'');
if(hasil == 'y')
{
alert("Data Berhasil di Update");
location.reload();
}
else
{
alert('Failed.');
}
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error update data');
}
});
}
}
else
{
alert('no data selected');
}
}
</script>
</div><!-- end cols-->
</div><!--end row-->
</div> <!-- end container-->
and this is my controller :
public function mesin_update()
{
$initiated_date = date('Y-m-d H:i:s');
$data = array(
'lastupdate_date' => $initiated_date,
);
$devids = $this->input->post('devid_auto', True);
foreach($devids as $devid){
$this->Jam_tgl_model->jam_tanggal_update(array('devid_auto' => $devid ), $data);
}
echo 'y';
}
and this is my model :
public function jam_tanggal_update($where, $data)
{
$this->db->update($this->table, $data, $where);
return $this->db->affected_rows();
}
I have tried it with my code but nothing has changed on column last update date
please help fix my code so i can finish it
( NEW EDIT) :
- this is the result:
- I checked the line
- and pressing the update button, can you change the script function update (id)?
- and this is the result after I hit update button
in contorller
$devids = $this->input->post('devid_auto', True);
foreach($devids as $devid){
$this->Jam_tgl_model->jam_tanggal_update(array('devid_auto' => $devid), $data);
}
NOTE: also you can use ci $this->db->update_batch()
Try this in your model
public function jam_tanggal_update($where, $data) {
$this->db->where($where);
$this->db->update($this->table_dept, $data);
return $this->db->affected_rows();
}
For More details on Updating: See CodeIgniter official documentation
Try This.. This May Help you .
Controller
public function delete_inbox()
{
$ids = ( explode( ',', $this->input->get_post('devid_auto') ));
$initiated_date = date('Y-m-d H:i:s');
$data = array(
'lastupdate_date' => $initiated_date,
);
$del= $this->model-mesin_update($ids,$data);
}
Model:
public function jam_tanggal_update($where, $data){
$ids = $ids;
$count = 0;
foreach ($ids as $id){
$did = intval($id);
$this->db->where('id', $did);
$res=$this->db->update('<table_name',$data);
$count = $count+1;
}
}

Display data in a table by its id after successful AJAX call

i have a search input field in my page. currently i am displaying data from the database successfully in a table(id="table_userinfo"). Now i want to add the live search functionality to my table(id="table_userinfo") as well. i am using php codeigniter.
in my user_model i have:
function search_userInfo($keyword)
{
$this->db->like('DeviceName',$keyword);
$this->db->or_like('RegistrationDateTime',$keyword);
$this->db->or_like('LastUpdateDateTime',$keyword);
$this->db->or_like('AppVersion ',$keyword);
$this->db->or_like('iOSVersion',$keyword);
$this->db->or_like('DeviceDID',$keyword);
$this->db->or_like('DeviceToken',$keyword);
$query = $this->db->get('userinfo');
if($query)
{
return $query->result();
}
else
{
return NULL;
}
}
in my login_controller:
function displayDatabase()
{
$data['tableInfo']=$this->user_model->fetchData();
$this->load->view('adminPanel_view',$data);
}
function search()
{
$search=$this->input->post('searchString');
$data['tableInfo']=$this->user_model->search_userInfo($search);
}
in my adminPanel_view page, i have:
<script>
$('#search').keyup(function(){
var input_data = {searchString: $('#search').val() };
//console.log(input_data);
$.ajax({
type:"POST",
url:base_url+'index.php/login_controller/search',
data:input_data,
success:function(data){
if(data.length>0)
{
console.log(data);
}
}
});
});
</script>
<table class="table table-bordered table-hover table-full-width" id="table_userinfo">
<thead>
<tr>
<th>Serial No.</th>
<th class="hidden-xs">Device Name</th>
<th>Device Type</th>
<th>RegistrationDateTime </th>
<th>LastUpdateTime</th>
<th>LastPushNotificationSent</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php //print_r ($tableInfo);exit;?>
<?php $no=0;?>
<?php foreach($tableInfo as $r): ?>
<tr>
<td><?php echo $no ?></td>
<td><?php echo $r->DeviceName ?></td>
<td><?php echo $r->DeviceType ?></td>
<td><?php echo $r->RegistrationDateTime ?></td>
<td><?php echo $r->LastUpdateDateTime ?></td>
<td><?php echo $r->LastPushNotificationSent ?></td>
<td><?php echo "Actions" ?></td>
</tr>
<?php $no+=1;?>
<?php endforeach; ?>
</tbody>
</table>
this is the search bar that i am using in addition to this table
<div id="" class="dataTables_filter">
<label>
<input placeholder="Search" class="form-control input-sm" aria-controls="sample_1" type="text" id="search" name="search_userinfo">
</label>
</div>
how do i display the data that i am getting through the Ajax call and show it in the table(id="search_userinfo).
inside of function search() return it as:
echo json_encode($this->user_model->search_userInfo($search));
and inside of javascript do this
<script>
$('#search').keyup(function(){
var input_data = {searchString: $('#search').val() };
//console.log(input_data);
$.ajax({
type:"POST",
url:base_url+'index.php/login_controller/search',
data:input_data,
dataType: "json",
success:function(data){
$("#table_userinfo").html(" "); //clear everything from table
data.forEach(function(entry) {
$("#table_userinfo").append("<td>"+entry.DeviceName+"</td><td>");
//just add everything here
});
}
});
});
</script>
Your Controller
function search()
{
$search=$this->input->post('searchString');
$data['tableInfo']=$this->user_model->search_userInfo($search);
print_r(json_encode($data['tableInfo']));exit
}
In your ajax add this line
dataType:'json';
Now In Your Success function You will get an json for that data ,You can append like this,
$.each(data, function(i, item) {
alert(item.DeviceName); // append data where you need to append
});​
But Please be sure about amount of data you get in success function, with keyup

unable to do inline editing with php code igniter and jquery. Not able to update table values in the database

this is my edit_table.php in which dynamic table is generated and by on click function i try to update database.
<script>
function table_edit(btn)
{
var id=btn.id;
if(btn.value=="Edit")
{
document.getElementById('college_id'+id).setAttribute("contenteditable" , "true");
document.getElementById('name'+id).setAttribute("contenteditable" , "true");
//document.getElementById('university_id'+id).removeAttribute("Readonly");
document.getElementById('university_id'+id).setAttribute("contenteditable" , "true");
document.getElementById(id).value="Save";
return false;
}
if(btn.value=="Save")
{
document.getElementById('name'+id).removeAttribute("contenteditable");
document.getElementById('college_id'+id).removeAttribute("contenteditable");
// document.getElementById('university_id'+id).setAttribute("Readonly" , "readonly");
document.getElementById('university_id'+id).removeAttribute("contenteditable");
document.getElementById(id).value="Edit";
var newuniversity_id=document.getElementById('university_id'+id).innerHTML;
var newcollege_id=document.getElementById('college_id'+id).innerHTML;
var newname=document.getElementById('name'+id).innerHTML;
alert(newname+" "+newcollege_id+" "+newuniversity_id+" "+id);
var dataString = 'name1=' + name + '&university_id=' + newuniversity_id + '&college_id=' + newcollege_id + '&id=' + id;
$.ajax({
type: "POST",
url: "update_table_data",
data: dataString,
success: function(html) {
alert("ajax calling done");
}
});
return true;
}
}
function table_update(){
//document.getElementById("edit_rows").value="Save"
alert("Working!");
}
</script>
<?php
function test()
{
echo "<script>alert('hello');</script>";
} ?>
<div id="page-content-wrapper">
<div class="container-fluid">
<i class="fa fa-bars"></i> <span>Menu</span>
<div class="content-block">
<div class="login-sign forgot_pass login forgot text-center">
<!-- <form action="<?php echo base_url(); ?>edit_table" method="post" accept-charset="utf-8"> -->
<div class="login-signup-head">Edit Table</div>
<table>
<tbody>
<thead>
<tr class="tredit">
<!-- <th width="10"></th> -->
<th> Id </th>
<th > University Id </th>
<th > Name </th>
<th > College Id </th>
<th width="100"> </th>
</tr>
</thead>
<tbody>
<?php
foreach($student_data as $row){
?>
<tr class="tredit" id="row_edit">
<td><?php echo $row['id']; ?></td>
<td id="university_id<?php echo $row['id']; ?>" ><?php echo $row['university_id']; ?></td>
<td id="name<?php echo $row['id']; ?>" ><?php echo $row['name']; ?></td>
<td id="college_id<?php echo $row['id']; ?>" > <?php echo $row['college_id']; ?></td>
<td><input type='button' class='editable' onclick=" return table_edit(this)" value='Edit' id= "<?php echo $row['id']; ?>">
<input type='button' class='tabledelete' onclick="table_update()" value='Delete' ></td>
</tr>
<?php
}
?>
</div>
</div>
</div>
<!-- </form> -->
</div>
</div>
</tbody>
</table>
and this is the route
$route['update_table_data'] = 'home/update_table';
and the following functions are for fetching the data as well as updating the data.
public function tableedit(){
if($this->session->userdata('university_id')){
$user_id = $this->session->userdata('university_id');
$data['user_id'] = $user_id;
$data['student_data'] = $this->home_model->table_data($user_id);
$this->load->view('home/new-header',$data);
$this->load->view('home/left_university_sidebar',$data);
$this->load->view('edit_table',$data);
$this->load->view('home/footer');
} else {
$data['error'] = 'Table Cannot be viewed!';
$this->load->view('home/header');
$this->load->view('edit_table');
$this->load->view('home/footer');
}
}
public function update_table() {
if($this->session->userdata('university_id')){
if($this->input->server("REQUEST_METHOD") === "POST"){
$university_id=$_POST['university_id'];
$college_id=$_POST['college_id'];
$id=$_POST['id'];
$name=$_POST['name'];
$this->home_model->update_table($university_id,$college_id,$name,$id);
}
}
}
and finally this is the model for update query.
public function update_table($university_id,$college_id,$name,$id) {
$data = array('University Id' => $university_id, 'name' => $name, 'College Id' => $college_id);
$this->db->where('id', $id);
$this->db->update('college', $data);
}
editable table
edit values
but when i save and refresh the page, no change occur in the table.
my issue is database is not updated when i update it from save button.
first of all :
Formatting your code , that must be clean and easily readable
for your ajax call you dont need use routed url , it work at background, you can use like this :
put : <script>var base_url='<?php echo base_url(); ?>'</script>
in your header menu , or upper place that you use in your theme.
then make ajax call like this:
$.ajax({
type: "POST",
url: base_url+"youController/yourAction",
data: dataString,
success: function(html) {
alert("ajax calling done");
}
});

AJAX call does not post the data

I am developing a web site with Code Igniter 2.1.3. I am using an AJAX call to post data to my controller, but for some reason the data is not being sent.
I am using AJAX calls all over the application and they all work well, just not this one.
My view:
<div id="ajaxResult">
<div class="page-header"><h2>Review Comments</h2></div>
<div class="row-fluid">
<div class="span12">
<?php if(count($comments)): ?>
<table class="table">
<thead>
<tr>
<th>Author</th>
<th>Email</th>
<th>IP Address</th>
<th>Date</th>
<th>Comment</th>
<th>Approve</th>
</tr>
</thead>
<tbody>
<?php foreach($comments as $comment): ?>
<tr>
<td>
<?php echo $comment->comment_author; ?>
</td>
<td><?php echo $comment->comment_author_email; ?></td>
<td><?php echo $comment->comment_author_IP; ?></td>
<td>
<?php
$date = new DateTime($comment->comment_date);
$date = $date->format('d/m/Y');
echo $date;
?>
</td>
<td>
<?php echo $comment->comment_content; ?>
</td>
<td>
<?php
$approve = array(
'name' => 'comment_approved',
'class' => 'approve',
'value' => '1',
'data-commentid' => $comment->id
);
echo form_checkbox($approve);
?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php else: ?>
<p>No comments were found for review.</p>
<?php endif; ?>
</div>
</div>
</div>
<script>
$(function()
{
$('.approve').on('click', function()
{
var id = $(this).data('commentid'); alert(id);
$.ajax({
url: "<?php echo site_url('blog/admin/review_comment'); ?>",
type:'POST',
data: { comment_id: id },
success: function(data) { $('#ajaxResult').html(data); } // End of success function of ajax form
}); // End of ajax call
});
});
</script>
My controller function:
public function review_comment()
{
$this->load->helper('form');
$this->load->model('blog_comment_m');
if(isset($_POST['comment_id']))
{
$id = $this->input->post('comment_id');
$data['comment_approved'] = 1;
$this->blog_comment_m->save($data, $id);
$this->data['comments'] = $this->blog_comment_m->get_by(array('comment_approved'=>0));
$this->load->view('admin/review_comments', $this->data);
}
else
{
$this->data['comments'] = $this->blog_comment_m->get_by(array('comment_approved'=>0));
$this->data['subview'] = 'admin/review_comments';
$this->load->view('admin/_layout_main', $this->data);
}
}
I tried to alert the comment_id and it does give me a value of 1. In the controller I do var_dump($_POST), always empty.
I also tried if(isset($_POST['comment_id'])). In the controller it never goes into the if(isset($_POST['comment_id']) statement.
Why is that?
Found it.
It was the fact that I started using csrf on form submits, a new thing for me, and I didn't add this url to the config file.
Adding this:
$config['csrf_exclude_uris'] = array('blog/admin/review_comment');
Solved the problem......
Thank you very very much for all the help.

Categories