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
Related
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?
I'm trying fill the table with fetched data from database by the id of selected option. Table content must change when user selects other option. Chosen plugin is working fine and select options is filled with correct values, how to give var selektas from test.php to loader.php in query where kliento_id = $idofclient?
Somehow make selektas == $idofclient so that i could use this variable in query in loader.php
My test.php:
<script type="text/javascript">
$(document).ready(function () {
$('.chosen-select').chosen();
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#.pavadinimai").on("change",function(){
var selektas = $(this).val().split('|');
$.ajax({
type: "POST",
url: "loader.php",
data: {selektas[o]},
success: function(result){
$("#show").html(result);
$('#show').dataTable().fnDestroy();
$('#show').dataTable();
}
});
});
});
</script>
<select class="chosen-select" name="pavname" id="pavadinimai">
<option selected="selected" value = "">---Pasirinkti---</option>
<?php
echo "Pasirinkite klienta";
$sql = "SELECT id, kliento_pav FROM klientai";
$stmt = mysqli_query($link, $sql);
while ($row = mysqli_fetch_assoc($stmt)) {
echo "<option value='" . $row['id'] .'|'. $row['kliento_pav'] . "'>" . $row['kliento_pav'] . "</option>";
}
list($idofclient,$pavofclient) = explode ('|',$_POST['pavname']);
?>
</select>
<div id="show">
</div>
And this is my code in loader.php
<?php
require_once "config.php";
if(isset($_POST["pavadinimas"])){
$sql_query="SELECT uzsakymai.id, kliento_id, uzsakymai.kiekis,prekes.pavadinimas,uzsakymai.aprasymas FROM uzsakymai INNER JOIN prekes ON uzsakymai.prekes_id = prekes.id INNER JOIN klientai on uzsakymai.kliento_id = klientai.id WHERE kliento_id = $idofclient"
$resultset = mysqli_query($link, $sql_query) or die("database error:". mysqli_error($link));
while( $result = mysqli_fetch_assoc($resultset) ) {
?>
<br>
<table id="data_table" class="table table-striped">
<thead>
<tr>
<th>Prekės pavadinimas</th>
<th>Kiekis</th>
<th>Aprašymas</th>
</tr>
</thead>
<tbody>
<tr id="<?php echo $result ['id']; ?>">
<td><?php echo $result ['pavadinimas']; ?></td>
<td><?php echo $result ['kiekis']; ?></td>
<td><?php echo $result ['aprasymas']; ?></td>
</tr>
</tbody>
</table>
<?php } ?>
<?php
echo $result
}
?>
I'm using ...jquery/3.1.1/jquery.min.js
Try this
Initially you initialized the table so first clear that table
$('#myTable').dataTable().fnDestroy();
Then initialize again after ajax success
$('#myTable').dataTable();
Like this.....
$(document).ready(function(){
$("#.pavadinimai").on("change",function(){
$.ajax({
type: "POST",
url: "loader.php",
data: {$idofclient},
success: function(result){
$("#show").html(result);
$('#show').dataTable().fnDestroy();
$('#show').dataTable();
}
});
});
});
$(document).ready(function() {
$("#pavadinimai").on("change", function() {
var pavadinimai = $("#pavadinimai").val();
$.ajax({
type: "POST",
url: "loader.php",
data: {
pavadinimai: pavadinimai
},
success: function(result) {
$("#show").html(result);
$('#show').dataTable().fnDestroy();
$('#show').dataTable();
}
});
});
});
I'm not looking to add to / append an existing table. My table is empty until results are returned via AJAX. I'm trying to sort my tables data via the javascript plugin, tablesorter.js.
I have sorted my table so It's split between header and body. I can't seem to get the table rows to change though
My Code for the AJAX is;
<script>
$(document).ready(function()
{
$("#results").tablesorter();
}
);
</script>
<script>
$(document).ready(function(){
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(function(){
$("#to_date").datepicker();
});
var to_date = $('#to_date').val();
$( "#genre" ).val();
{
var value = $(this).val();
$( "#price" ).val();
{
var value = $(this).val();
$('#filter').click(function(){
var to_date = $('#to_date').val();
var request = $("#genre").val();
var request1 = $("#price").val();
var data = 'to_date'+'request'+'request1';
if(to_date != '' )
{
$.ajax({
url:"filter.php",
method:"POST",
data: { to_date:to_date, request:request,request1:request1 },
success:function(data)
{
$('#results').html(data);
$('#results').trigger("update");
}
});
}
else
{
alert("Please Select Date");
}
});
};
};
});
</script>
and my code for the html / PHP is;
<table id="results" class="tablesorter">
<thead>
<tr>
<th>Event</th>
<th>Venue</th>
<th>Genre</th>
<th>Date</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $row["event_name"]; ?></td>
<td><?php echo $row["venue_name"]; ?></td>
<td><?php echo $row["genre"]; ?></td>
<td><?php echo $row["event_date"]; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
you never actually called to the plugin:
$("results").tablesorter()
Everytime you get your data updated you should make a all to the tablesorters update trigger so it gets its references updated.
success:function(data)
{
$('#results').html(data);
$('#results').trigger("update");
}
that should do the trick
I need a solution for this. Here is what I am trying to do. I have a datatable that has some values and check boxes in the first columns. What I need is when I select the check box in the header it should select all the values in the current page only. But all the check boxes of all the pages get selected.
I also want that, When I navigate to another page of the datatable, the check box selections of all the previous page should be unchecked including the check box in the header.
Hear is my code:
<?php if($acl->can('view_article')){ ?>
<table id="articles" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<?php if($acl->can('delete_article')){ ?>
<th><input id="select_all_existent" type="checkbox" /></th>
<?php } ?>
<th>Article</th>
<th>Categories</th>
<th>Demographic</th>
<th>Intended Month</th>
<th class="text-right">Word Count</th>
</tr>
</thead>
<tbody>
<?php
foreach($articles as $article) {
$id = $article["id"];
$uid = $article["uid"];
$article_name = $article["article_name"];
$article_file_path = $article["article_file_path"];
$article_category = $article["article_category"];
$article_demographic = $article["article_demographic"];
$article_word_count = $article["article_word_count"];
$intended_month = $article["intended_month"];
$article_created = $article["article_created"];
if(!empty($article_demographic)) {
$article_demographic = implode(", ",$article_demographic);
}
$article_keywords = $article["article_keywords"];
$article_description = $article["article_description"];
$checkbox = in_array($id, $assigned_articles)? " ":"<input type='checkbox' value=".$id." />";
echo "
<tr class='' data-id='$id'>
" ;
if($acl->can('delete_article'))
echo "<td>$checkbox</td>";
if($acl->can('edit_article')){
echo "<td>" . anchor("articles/edit/$id",$article_name.'- '.$article_word_count,"class='notBtn' title=\"$article_description\"") . " </td>";
}else{
echo "<td>$article_name - $article_word_count</td>";
}
echo "
<td>".short_string($article_category)."</td>
<td>".short_string($article_demographic)."</td>
<td> $intended_month </td>
<td align='right'>$article_word_count</td>
</tr>";
}
?>
</tbody>
</table>
<?php } ?>
<script type="application/javascript">
$(document).on( 'init', function ( e, settings ) {
alert( 'Saved page length is: '+ table.state().length );
} );
$(document).ready(function(){
var oTable = $("#articles").DataTable({
"stateSave": true,
"order": [],
"dom": '<"row" <"col-md-12 space" <"datatable-action pull-left"> <"datatable-n pull-right" l > > >rt <"row" <"col-md-6" i > <"col-md-6" p > >',
"columns" : [
<?php if($acl->can('delete_article')){ ?>
{orderable: false, searchable: false},
<?php } ?>
{"width": "25%" },
null,
null,
{"width": "12%" },
{"width": "10%" },
],
"fnDrawCallback": function( oSettings ) {
$('.popupArticle').viewArticle({
url : '<?=site_url("articles/showArticleInPopup");?>',
title : 'Article Preview',
size : 'lg'
});
}
});
$('#search-inp').on('keyup',function(){
oTable.search($(this).val()).draw() ;
})
if(oTable.state().length != 0)
$('#search-inp').val(oTable.state().search.search);
checkAllCheckbox(oTable);
var deletebtn = '';
<?php if($acl->can('delete_article')){ ?>
var deletebtn = '<i class="fa fa-trash-o"></i>';
<?php } ?>
var assignbtn = '';
<?php if($acl->can('assign_article')){ ?>
var assignbtn = '<i class="fa fa-paperclip"></i>';
<?php } ?>
$("div.datatable-action").html(deletebtn + ' ' +assignbtn);
$('#assignbtn').on('click', function (e) {
e.preventDefault();
eModal.setEModalOptions({loadingHtml : ''});
eModal.iframe('<?= site_url("assignArticles/e/"); ?>', 'Assign Article').then(function (input) {
$('.modal-dialog', window.document).css('width', '80%');
if ($('.modal-footer', window.document).length == 0) {
$('.modal-content', window.document).append('<div class="modal-footer"> </div>');
}
});
});
});
</script>
Here is the code for checkAllCheckbox(oTable);
function checkAllCheckbox(oTable) {
/* Check all in Datatable*/
if ($("#select_all_existent").length != 0) {
var cells = oTable.cells().nodes();
$("#select_all_existent").change(function () {
$(cells).find(":checkbox").prop("checked", $(this).is(":checked"));
});
$(cells).find(":checkbox").change(function(){
if(!$(this).is(":checked")){
$("#select_all_existent").prop("checked", $(this).is(":checked"));
}
else{
if ($(cells).find(":checkbox").length == $(cells).find(":checked").length) {
$("#select_all_existent").prop("checked",true);
}
}
if ($(cells).find(":checked").length > 0) {
$(oTable.table().container()).siblings().find('.help- block').html('');
}
else{
$(oTable.table().container()).siblings().find('.help- block').html('Please select at least one checkbox');
}
});
}
}
Any help on the scenarios that I have mentioned would be appreciated.
In your code made the following changes and try:
change 1: disable sorting of checkbox column
<thead>
<tr>
<?php if($acl->can('delete_article')){ ?>
<th data-orderable="false"><input id="select_all_existent" type="checkbox" /></th>
<?php } ?>
<th>Article</th>
<th>Categories</th>
<th>Demographic</th>
<th>Intended Month</th>
<th class="text-right">Word Count</th>
</tr>
</thead>
change 2:
add the following code to script:
$('#articles').on('page.dt', function() {
$('#select_all_existent').prop("checked", 0);
$('#select_all_existent').trigger('change');
});
$('#articles').on('length.dt', function() {
$('#select_all_existent').prop("checked", 0);
$('#select_all_existent').trigger('change');
});
$('#select_all_existent').on('change',function () {
checkAllCheckbox(oTable);
});
Please help me. Thanks in advance. Actually I am trying to insert selected checkbox rows into database using jquery but i don't know how to insert into DB.My jquery code is selecting the row but how to check whether the row is passing through ajax request. My table has a dynamic row from the database table with checkboxes. so when i checked the checkboxes and click the submit button then the table row should insert into the database table.
My code as below:
test.php
<?php
$con = mysql_connect("localhost","root","");
if(!$con)
{
die("Could not connect:".mysql_error());
}
mysql_select_db("cakephp",$con);
$sql = mysql_query("select * from carts where userid=13");
?>
<html>
<head>
<title></title>
<script src="jquery.js"></script>
<script src="jquery.validate.min.js"></script>
<script src="jquery-ui.min.js"></script>
<style type="text/css">
.row_selected {background-color: #BFCBD7;}
</style>
<script>
$(document).ready(function(){
$('.chk').on('change', function() {
//alert('Hai');
var thisCheckbox = $(this);
var thisRow = thisCheckbox.closest('tr');
if ( thisCheckbox.is(':checked') ) {
thisRow.addClass('row_selected');
} else {
thisRow.removeClass('row_selected');
};
});
$('#orderSave').on('click', function(row,tr) {
//e.preventDefault();
//var toPost = $('.row_selected input').serialize();
/* Now post and insert into database */
//$.post('/invl_exams/ordercompletion', toPost, function(data) {
//alert('Success!');
//});
// Here i am creating the array to hold each selected row
var TableData = new Array();
var priVal = $(tr).find('td:eq(6)').text();
var priceVal = priVal.replace('$','');
TableData[row] = {
//column names: corresponding row data
"userid" : $('#userid').val(),
"username" : $('#hiddenUser').val(),
"date" : $(tr).find('td:eq(3)').text(),
"exam" : $(tr).find('td:eq(4)').text(),
"venue" : $(tr).find('td:eq(5)').text(),
"price" : priceVal,
"total_orders" : $(tr).find('td:eq(7)').text(),
"amount" : $(tr).find('td:eq(8)').text(),
"orders_completion" : $(tr).find('td:eq(9)').text()
}
TableData = JSON.stringify(TableData);
//console.log(TableData);
$.ajax({
type : "POST",
url : "testsubmit.php",
cache : "false",
data : {data:TableData},
success : function(result){
console.log(result);
}
});
});
});
</script>
</head>
<body>
<table border="1">
<tr>
<th>S.No</th>
<th>Exam Name</th>
<th>Venue</th>
<th>Date</th>
<th>Price</th>
<th>No of Orders</th>
<th>Amount</th>
<th>Checks</th>
</tr>
<?php
$i=1;
while($row = mysql_fetch_array($sql))
{
?>
<tr>
<td><?php echo $i++;?></td>
<td style="display:none" id="userid">13</td>
<td style="display:none" id="hiddenUser">Gautham</td>
<td><?php echo $row['exam_name'];?></td>
<td><?php echo $row['venue'];?></td>
<td><?php echo $row['date'];?></td>
<td><?php echo $row['price'];?></td>
<td><?php echo $row['noOf_orders'];?></td>
<td><?php echo $row['amount'];?></td>
<td><input type="checkbox" name="chk" class="chk" value="1"></td>
</tr>
<?php
}
?>
<tr>
<td colspan="7"> </td>
<td><button type="button" class="btn btn-success btn-xs" id="orderSave">Submit</button></td>
</tr>
</table>
</body>
</html>
testsubmit.php ( In this file i was checking the post request using print_r($_POST) )
<?php
$con = mysql_connect("localhost","root","");
if(!$con)
{
die("Could not connect:".mysql_error());
}
mysql_select_db("cakephp",$con);
//if(isset($_POST['toPost']))
//{
print_r($_POST);
//}
?>
your data inside last td is an input so you must
change from
"orders_completion" : $(tr).find('td:eq(9)').text()
to
"orders_completion" : $(tr).find('.chk')[0].checked