I have the following Datatable
<br><button id="addRow">Add New Row</button><br>
<table class="table table-striped table-bordered table-hover " id="example" cellSpacing=0 width="100%">
<thead>
<tr>
<th>Image</th>
<th>number</th>
<th>Creation_date</th>
<th>ei</th>
<th>name</th>
<th>profit</th>
</tr>
</thead>
<?php
foreach ( $data_req_table as $k => $v ) :
?>
<tr style="text-align: center;">
<td>
<img width="100px"
data-original="image.jpg"
src="image.jpg"
/>
</td>
<td><? echo $v['number']; ?></td>
<td><? echo $v['creationdate']; ?></td>
<td><? echo $v['ei']; ?></td>
<td><? echo $v['name']; ?></td>
<td><? echo $v['profit']; ?></td>
</tr>
<?php
endforeach;
?>
</table>
on which I add rows trough a Jquery - Ajax script. following :
<script type="text/javascript">
$(document).ready(function () {
debugger;
var t = $('#example').DataTable({
"searching": true,
//"paging": true,
"order": [[ 2, "desc" ]],
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
], iDisplayLength: -1
});
var counter = 1;
$('#addRow').on('click', function ciicici() {
var now = new Date();
var now = now.toMysqlFormat();
var tii = new Date();
tii.setSeconds(tii.getSeconds() - 15);
var tii = tii.toMysqlFormat();
//alert(tii);
$.post( "sql.php", { timing: now,seconding: tii })//.done({});
.done(function( data ) {
var dataParts = data.split("##")
var lenghtylenght = dataParts.length;
for (i = 0; i <= lenghtylenght; i++) {
var dataPart = dataParts[i];
var splitData = dataPart.split("///");
t.row.add([
splitData[0],
splitData[1],
splitData[2],
splitData[3],
splitData[4],
splitData[5]
]).draw();
alert('done');
}
counter++;
});
//setTimeout(function(){ciicici();}, 15000);
});
$('#addRow').click();
});
</script>
and the php being
$ippi = 0;
foreach ( $data_rreq as $k => $v ) : //data_rreq is the pdo fetched array
$ippi++;
echo "<td><img width='100px' src='image.jpg' /></td>".'///';
echo '<td>'.$v['number'].'</td>'.'///';
echo '<td>'.$v['creationdate'].'</td>'.'///';
echo '<td>'.$v['ei'].'</td>'.'///';
echo '<td>'.$v['name'].'</td>'.'///';
echo '<td>'.$v['profit'].'</td>';
if($ippi < $len){
echo "##";
}
endforeach;
The code works but I have 2 problems :
1) Datatable problem, everytime a row is automatically added, I get an error : Requested unknown parameter '1' for row ... . It looks like it loops once too much, it doesn't find any results and it has an error. My datatable reference being the following :
<script src="http://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.0/js/jquery.dataTables.min.js"></script>
2) And then I wanted to ask wether there is a way to avoid using the split function to puss 5 different parameters to a request, using may be some sort of json encoded arrays.
markoc
I think your loop need to be patched:
for (i = 0; i <= lenghtylenght; i++)
Replace with:
for (i = 0; i < lenghtylenght; i++)
Else you will go outofindex.
Related
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
I have a user table in my panel using following Php code :
<html>
<body>
<div id="order_table">
<table>
<thead>
<tr>
<th>Name</th>
<th>Mobile</th>
</tr>
</thead>
<?php
Include_once("db/connection.php");
$stmt_select_users = $conn->prepare("SELECT name,mobile FROM api_user order by create_date DESC limit 5;");
$stmt_select_users->execute();
while ($row_select_users = $stmt_select_users->fetch(PDO::FETCH_ASSOC)) {
?>
<tr>
<td><?php echo $row_select_users['name']; ?></td>
<td><?php echo $row_select_users['mobile']; ?></td>
</tr>
<?php
}
?>
</table>
</div>
</body>
</html>
I know about following function :
$(document).ready(function () {
setInterval(function () {
$("#order_table").load("users_table.php")
}, 3000);
});
but I don't want to update the full table, Just if a row inserted, table add that row. Any help?
You should create a PHP file that returns only the records you want and manipulate the table with javascript.
Assuming you have that script that returns the HTML table row element like:
<tr>
<td>Some value</td>
<td>Another value</td>
</tr>
You can do something like that.
$(document).ready(function () {
setInterval(function () {
$.get("my-script.php", function(data) {
$("#order_table table").append(data);
});
}, 3000);
});
For more information http://api.jquery.com/append/ and https://api.jquery.com/jquery.get/
I hope I could help.
EDIT: Code example
Disclaimer: This is a really simple code snippet and you should perform validations and optimizations.
<?php
// request.php
$data = [
['valor 1 - linha 1', 'valor 2 - linha 1'],
['valor 1 - linha 2', 'valor 2 - linha 2'],
['valor 1 - linha 3', 'valor 2 - linha 3'],
];
$afterIndex = $_GET['afterIndex'];
$count = sizeof($data);
$tableRows = [];
if ($afterIndex < $count) {
for ($i = $afterIndex; $i < $count; $i++) {
$item = $data[$i];
$tableRows[] = '<tr><td>' .$item[0] . '</td><td>' . $item[1] . '</td></tr>';
}
}
echo json_encode([
'index' => $count,
'rows' => $tableRows
]);
The data array is a simulation of your database, modify the code to your needs.
<script>
document.addEventListener('DOMContentLoaded', function() {
$(document).ready(function () {
var index = 0;
setInterval(function () {
$.get("/request.php?afterIndex="+index, function(data) {
var response = JSON.parse(data);
index = response.index;
for (var i = 0; i < response.rows.length; i++) {
$("#order_table table tbody").append(response.rows[i]);
}
});
}, 3000);
});
});
</script>
The script above makes a request to the php code and render the response rows in the table.
The table is something like:
<div id="order_table">
<table>
<thead>
<tr>
<th>1</th>
<th>2</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
i have this table wrote in html with php and bootstrap:
<table id="tabela-resultado" class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th>Nome</th>
<th>Ativo</th>
<th class="text-center">Ação</th>
</tr>
</thead>
<tbody>
<?php if(count($records)) { ?>
<?php foreach($records as $record) { ?>
<tr data-id="<?php echo $record->id; ?>">
<td><?php echo $record->nome; ?></td>
<td>
<?php
if ($record->ativo == 1) {
echo "SIM";
} else if($record->ativo == 0){
echo "NÂO";
}
?>
</td>
<td>
<?php echo anchor("gurpoProduto/excluir", "<i class='glyphicon glyphicon-trash'></i> Exlcuir", ['class' => 'btn btn-danger btn-block', 'name' => 'delete']); ?>
</td>
</tr>
<?php
}
}
?>
</tbody>
</table>
i'm trying to found an element in the first column using this function with jquery. Tihs is the function:
function verificar_existencia(nome) {
var table = $("#tabela-resultado tbody");
var nomeTabela = '';
table.find('tr').each(function (nome) {
var $tds = $(this).find('td'),
nomeTabela = $tds.eq(0).text()
});
if(trim(nome.toUpperCase()) === trim(nomeTabela.toUpperCase())) {
toastr.success("This element already exists!!!", "Aviso");
//return false;
}
}
but doesnt work.Whats is wrong? I need find an element in the table to prevent duplicate elements in the table.
You are looping through all the rows and overwriting nomeTabela every iteration.
Thus once loop completes it is the value found in last row only and that is what your comparison is done on
Do a check inside the loop for each value on each row something like:
function verificar_existencia(nome) {
nome = nome.trim().toUpperCase();
var table = $("#tabela-resultado tbody");
var isMatch = false;
table.find('tr').each(function(nome) {
var $tds = $(this).find('td');
var nomeTabela = $(this).find('td').eq(0).text();
// compare each value inside the loop
if (nome === nomeTabela.trim().toUpperCase()) {
isMatch = true;
return false; /// break the loop when match found
}
});
if (isMatch) {
toastr.success("This element already exists!!!", "Aviso");
//return false;
}
}
Also note your incorrect use of String#trim() which should show up as error in your browser console
Here's a way to identify a dupe strings in the first column of the table.
var $trs = $("table tr"), dupes = [];
function san(str) {
return str.text().trim().toUpperCase();
}
$trs.each(function() {
var origTd = $(this).find("td:first"), origTr = $(this);
$trs.each(function() {
var newTd = $(this).find("td:first"),
newTr = $(this),
origTrIdx = origTr.index(),
newTrIdx = newTr.index(),
origTdStr = san(origTd),
newTdStr = san(newTd);
if (
origTrIdx > newTrIdx &&
dupes.indexOf(origTdStr) < 0 &&
origTdStr === newTdStr
) {
dupes.push(origTdStr);
console.log(
'This element "' +
origTd.text() +
'" already exists!!!'
);
return false;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<table>
<tr>
<td>foo</td>
<td>bar</td>
</tr>
<tr>
<td>foo</td>
<td>bar</td>
</tr>
<tr>
<td>unique</td>
<td>bar</td>
</tr>
<tr>
<td>unique2</td>
<td>bar</td>
</tr>
<tr>
<td>unique2</td>
<td>bar</td>
</tr>
<tr>
<td>unique2</td>
<td>bar</td>
</tr>
<tr>
<td>foo</td>
<td>bar</td>
</tr>
</table>
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);
});
I am trying to make a "td" disappear whenever the date occured before that date today (in the past). But what is happening is that only the first column is affected while the others aren't.
<script type="text/javascript">
//<![CDATA[
function vanish() {
downloadUrl("bckendcommmap.php", function(data) {
var xml = data.responseXML;
var markers50 = xml.documentElement.getElementsByTagName("marker50");
// Split timestamp into [ Y, M, D, h, m, s ]
for (var i = 0; i < markers50.length; i++) {
var newdate = markers50[0].getAttribute("date");
var trainid = markers50[0].getAttribute("trainingid");
var t = newdate.split(/[- :]/);
// Apply each element to the Date function
var d = new Date(t[0], t[1]-1, t[2]);
alert(d);
var rightNow = new Date();
var trainingDate = new Date(d);
if (rightNow < d ) {
document.getElementById("assess").innerHTML = ""; /* make it disappear */
}
else if (rightNow > d ) {
document.getElementById("edit").innerHTML = "";
}
// -> Wed Jun 09 2010 13:12:01 GMT+0100 (GMT Daylight Time)
}
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
</script>
Here are parts of the table and the td:
<body onload="vanish();">
<table id="gradient-style" width="290" border="0" cellspacing="0" cellpadding="0" >
<thead>
<tr>
<td align="center"><strong> Training Name</strong></td>
<td align="center"><strong> Description</strong></td>
<td align="center"><strong> Location</strong></td>
<td align="center"><strong> Date</strong></td>
<td align="center"><strong> Time Start</strong></td>
<td align="center"><strong> Time End</strong></td>
<td align="center"><strong> Capacity</strong></td>
<td align="center" colspan="2"><strong>Actions</strong></td>
</tr>
</thead>
<?php
while($rows=mysql_fetch_array($get)){
?>
<tbody>
<tr>
<td><?php echo $rows['title']; ?></td>
<td><?php echo $rows['description']; ?></td>
<td><?php echo $rows['location']; ?></td>
<td><?php echo $rows['date']; ?></td>
<td><?php echo $rows['start']; ?></td>
<td><?php echo $rows['end']; ?></td>
<td><?php echo $rows['capacity']; ?></td>
**<td align="center"><div id="edit">Edit</div></td><td align="center"><div id="assess">Assess Training</div></td>**
</tr>
</tbody>
<?php
}
?>
</table>
</body>
This line is the td that I'm trying to vanish with respect to the date:
<td align="center"><div id="edit">Edit</div></td><td align="center"><div id="assess">Assess Training</div></td>
You are only hiding the div, if you want to hide td Try this:
**<td id="edit" align="center"><div>Edit</div></td><td id="assess" align="center"><div>Assess Training</div></td>**
And the html code is inside a while loop so you will have multiple div's with same id! You need to give them unique ids:
$i = 0;
while($rows=mysql_fetch_array($get)){
/* Code... */
<?php
$i = $i + 1;
}
?>
And
<div id="assess<?php echo $i ?>>
And in your javascript:
/* Code... */
if (rightNow < d ) {
var i = 0;
while(document.getElementById("assess" + i) != null) {
document.getElementById("assess").innerHTML = ""; /* make it disappear */
i++;
}
/* Code.../
It's a bit hard to tell what the resulting full HTML in the page looks like, but do you realize that you can only have one object in a web page with a given ID. So, you can't have multiple objects with id="assess". If that is what you're doing, then getElementById will likely only return the first one - though the exact behavior is undefined because it's not valid HTML.
Second, why not just use CSS to hide things rather than clearing the innerHTML. For example, you could use a class="assess" instead of the id="assess". And, then create a CSS rule like this:
.triggerHide .assess {display: none;}
Then, when you want to hide that all assess classes in the table, you simple add the class "triggerHide" to the table. Boom, all the objects with the class assess in the table will all hide.