MDL Checkbox Function MaterialCheckbox.check() doesn't work on ajax content - javascript

I am working with MDL Checkbox where i need to delete all values at once. As i did some research and looks like old method is deprecated : Deprecations for MDL Data Table Checkbox and mdl-data-table--selectable can't be used anymore.
HTML Code:
<div class="load_customer">
<table class="mdl-data-table mdl-js-data-table mdl-shadow--2dp mdl-cell mdl-cell--12-col mdl-cell--12-col-tablet mdl-cell--7-col-phone">
<thead>
<tr>
<th>
<label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect mdl-data-table__select" id="table-header" for="table-input">
<input type="checkbox" id="table-input" class="mdl-checkbox__input" />
</label>
</th>
<th>Sr. No</th>
<th>Name</th>
<th>Gender</th>
<th>Date of Birth</th>
<th>Anniversary</th>
<th>Address</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<?php
$i=1;
$select = $pdo->query("SELECT * FROM `accounts` ORDER BY `id` DESC");
while($fetch = $select->fetch()){
?>
<tr>
<td>
<label class="mdl-checkbox child_checkbox mdl-js-checkbox mdl-js-ripple-effect mdl-data-table__select" data="<?php echo $fetch['id'];?>" for="row[<?php echo $i;?>]">
<input type="checkbox" id="row[<?php echo $i;?>]" class="mdl-checkbox__input" />
</label>
</td>
<td><?php echo $i;?></td>
<td><?php echo $fetch['name'];?> </td>
<td><?php echo $fetch['gender'];?></td>
<td><?php echo $fetch['dob'];?></td>
<td><?php echo $fetch['anniversary'];?></td>
<td><?php echo $fetch['address'];?></td>
<td><?php echo $fetch['phone'];?></td>
</tr>
<?php
$i++;
}
?>
</tbody>
</table>
</div>
So after adding it manually it works fine until i load table with ajax. Then it all stops working. I am able to check main checkbox #table-header, but function which checks all checkboxes (MaterialCheckbox.check()) does not works anymore. I checked console & there are no errors in console.
Javascript Code
var arr = [];
$(document).on("click","#table-header input",function() {
var all_elements = document.querySelectorAll('.child_checkbox');
for(var i=0, n=all_elements.length; i<n; i++){
var element = all_elements[i];
if($('#table-header input').is(":checked")) {
element.MaterialCheckbox.check();
var ids = element.getAttribute("data");
arr.push(ids);
}
else {
element.MaterialCheckbox.uncheck();
var removeItem = element.getAttribute("data");
arr = $.grep(arr, function(value) {
return value != removeItem;
});
}
}
});
I am using componentHandler.upgradeAllRegistered() and Checkbox is working fine, but it does not loop through all checkboxes.
$.post("load_customer.php",function(data){
$(".load_customer").html(data);
componentHandler.upgradeAllRegistered();
});
Please help me with this.Thanks.

Related

Display Updated table without refreshing or reloading page

I have a table which shows the list of my products and I have used jQuery to delete products without reloading the page, however the updated table doesn't show unless I refresh the page..
I have tried to hide it by using opacity, still it doesn't work..
Here is my php code
<div class="table-stats order-table ov-h">
<table id="bootstrap-data-table" class="table ">
<thead>
<tr>
<th>Image</th>
<th>Name</th>
<th>Availability</th>
<th>Category</th>
<th>Total Ordered</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody id="data-table">
<?php
$stmt_1 = mysqli_prepare($link,"SELECT * FROM products");
mysqli_stmt_execute($stmt_1);
$result = mysqli_stmt_get_result($stmt_1);
while($row = mysqli_fetch_array($result)){ ?>
<div class="product">
<tr class="product">
<?php
$sql_img = "SELECT * FROM pro_images WHERE pro_id= ? LIMIT ?";
$stmt_img = mysqli_prepare($link, $sql_img);
mysqli_stmt_bind_param($stmt_img, "ii" ,$param_pro_id, $param_limit);
$param_pro_id = $row["pro_id"];
$param_limit = 1;
mysqli_stmt_execute($stmt_img);
$img_results = mysqli_stmt_get_result($stmt_img);
$image = mysqli_fetch_assoc($img_results);
?>
<td><img src="../admin/assets/img/products/<?php echo $image["pro_image"]; ?>"></td>
<td><?php echo $row["pro_name"]; ?></td>
<td><?php echo $row["pro_quantity"]; ?></td>
<?php
$sql_category = "SELECT cat_name FROM categories WHERE cat_id = ?";
$stmt_category = mysqli_prepare($link, $sql_category);
mysqli_stmt_bind_param($stmt_category, "i", $param_cat_id);
$param_cat_id = $row["pro_category"];
mysqli_stmt_execute($stmt_category);
$result_category = mysqli_stmt_get_result($stmt_category);
$category = mysqli_fetch_assoc($result_category);
?>
<td> <?php echo $category["cat_name"]; ?> </td>
<?php
$pro_ord = "SELECT COUNT(*) AS total FROM order_details WHERE pro_id = ?";
$pro_stmt = mysqli_prepare($link, $pro_ord);
mysqli_stmt_bind_param($pro_stmt ,"i", $row["pro_id"]);
mysqli_stmt_execute($pro_stmt);
$pro_res = mysqli_stmt_get_result($pro_stmt);
$pro = mysqli_fetch_array($pro_res);
?>
<td><?php echo $pro["total"]; ?></td>
<td><span class="badge badge-success"><i class="ti-pencil"></i></span>
</td>
<td>
<button class="remove badge badge-danger" onclick="delete_data(<?php echo $row["pro_id"]; ?>)"><i class="ti-trash"></i></button>
</td>
</tr>
</div>
<?php } ?>
</tbody>
</table>
</div>
And here is my JQUERY code
function delete_data(d){
    var id=d;
if (confirm("Are you sure you want to delete this product? This cannot be undone later.")) {
 $.ajax({
      type: "post",
      url: "products.php",
      data: {id:id},
      success: function(){
        $(this).parents(".product").animate("fast").animate({ opacity : "hide" }, "slow");
      }
    });
}
  }
And here is the delete code
$pro_id =$_POST['id'];
$delete = "DELETE FROM products WHERE pro_id= ?";
$results = mysqli_prepare($link, $delete);
mysqli_stmt_bind_param($results, "i", $param_pro_id);
$param_pro_id = $pro_id;
mysqli_stmt_execute($results);
You need to be more specific when you targeting the div you want to refresh, for example:
success: function(){
$("#div_id_you_want_refresh")
.load("your_entire_url" + "#div_id_you_want_refresh");
}
You can pass this as well inside your delete_data function where this refer to current element clicked i.e : your button . Then , inside success function use this to hide your .product element.
Demo Code:
function delete_data(d, el) {
var id = d;
if (confirm("Are you sure you want to delete this product? This cannot be undone later.")) {
/* $.ajax({
type: "post",
url: "products.php",
data: {
id: id
},
success: function() {*/
//use this then remove closest product tr
$(el).closest(".product").animate("fast").animate({
opacity: "hide"
}, "slow");
/* }
});*/
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="bootstrap-data-table" class="table">
<thead>
<tr>
<th>Image</th>
<th>Name</th>
<th>Availability</th>
<th>Category</th>
<th>Total Ordered</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody id="data-table">
<tr class="product">
<td><img src="../admin/assets/img/products/"></td>
<td>
smwthing
</td>
<td>
1
</td>
<td>
abs
<td>
1222
</td>
<td><span class="badge badge-success"><i class="ti-pencil"></i></span>
</td>
<td>
<!--pass `this` inside fn-->
<button class="remove badge badge-danger" onclick="delete_data('1',this)"><i class="ti-trash">x</i></button>
</td>
</tr>
<tr class="product">
<td><img src="../admin/assets/img/products/"></td>
<td>
smwthing
</td>
<td>
12
</td>
<td>
abs1
<td>
12221
</td>
<td><span class="badge badge-success"><i class="ti-pencil"></i></span>
</td>
<td>
<button class="remove badge badge-danger" onclick="delete_data('2',this)"><i class="ti-trash">x</i></button>
</td>
</tr>
</tbody>
</table>

'Copy to the clipboard' button works only on the first page of DataTables

I have a data table in which there are columns and rows and one of them is a copy button which onclick() initiates a copy function and copies a particular row to the clipboard, it works normally on the first page but when I use the search or the pagination it does not work and the button does not initiate the javascript function.
I searched and found in StackOverflow that I need to reinitiate the data table, which I tried but it gives an error
DataTables warning: table id=datatable - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3
i have used the modified code that I tried after I searched StackOverflow after which it gives an error
DataTables warning: table id=datatable - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3
('#datatable').dataTable({ "fnDrawCallback": function(oSettings) {
//code
}});
});
<table id="datatable" class="table table-striped table-bordered" class="dass">
<thead>
<tr>
<th>No.</th>
<th>Student ID</th>
<th>Reference</th>
<th>First Name</th>
<th>Last Name</th>
<th>Copy</th>
</tr>
</thead>
<tbody>
<?php
$numm=1;
$stmt = $DB_con->prepare("SELECT * FROM asd);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{ ?>
<tr>
<td>
<?php echo $row['id']; ?>
</td>
<td>
<?php echo strtoupper($row['stid']); ?>
</td>
<td>
<?php echo $row['ref']; ?>
</td>
<td>
<?php echo $row['fname']; ?>
</td>
<td>
<?php echo $row['lname']; ?>
</td>
<td>
<button onclick="textToClipboard<?php echo $numm;?>()">Copy</button>
</td>
<th>
<script>
function textToClipboard <?php echo $numm;?> () {
var space = " ";
var x = document.getElementById('datatable').rows[<?php echo $numm;>].cells[1].innerHTML;
var y = document.getElementById('datatable').rows[<?php echo $numm;?>].cells[2].innerHTML;
var z = document.getElementById('datatable').rows[<?php echo $numm;?>].cells[3].innerHTML;
var text = x.concat(space, y, space, z, space, q, space, w);
var dummy = document.createElement("textarea");
document.body.appendChild(dummy);
dummy.value = text;
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
}
</script>
</th>
</tr>
<?php $numm++;
} ?>
</tbody>
How can I bind it with the data table?
It's not really a good practice to redefine a function again and again in a loop like this - that is what's parameters are for. I can't test this code, but here's an approach i would recommend:
<script>
function textToClipboard(numm) {
var space = " ";
var x = document.getElementById('datatable').rows[numm].cells[1].innerHTML;
var y = document.getElementById('datatable').rows[numm].cells[2].innerHTML;
var z = document.getElementById('datatable').rows[numm].cells[3].innerHTML;
var text = x.concat(space,y,space, z,space, q,space, w);
var dummy = document.createElement("textarea");
document.body.appendChild(dummy);
dummy.value = text;
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
}
</script>
<table id="datatable" class="table table-striped table-bordered"
class="dass">
<thead>
<tr>
<th>No.</th>
<th>Student ID</th>
<th>Reference</th>
<th>First Name</th>
<th>Last Name</th>
<th>Copy</th>
</tr>
</thead>
<tbody>
<?php
$numm=1;
$stmt = $DB_con->prepare("SELECT * FROM asd");
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<tr><td><?php echo $row['id']; ?></td>
<td><?php echo strtoupper($row['stid']); ?>
</td>
<td><?php echo $row['ref']; ?></td>
<td><?php echo $row['fname']; ?></td>
<td><?php echo $row['lname']; ?></td>
<td><button onclick="textToClipboard(<?php echo $numm;?>)">>Copy</button></td>
</tr>
<?php
$numm++;
} ?></tbody>
So define one parametered function first, and then call that later.
Furthermore, I'm unsure on how datatables handles selecting .rows[numm] after you search or use the pagination function. Therefore an even safer solution would involve passing all your required parameters in the function call, something like this:
onClick="textToClipboard($row['ref'], $row['fname'], $row['lname'])"
But this relies entirely on what you're trying to achieve here.
To avoid Cannot reinitialise DataTable Warning, just add
"destroy": true,
while initialising it. That will reinitialise a datatable again when you call it second time.
Read more:
https://datatables.net/reference/option/destroy
https://datatables.net/reference/api/destroy() -- destroy method

onclick() does not work in a table

i created an appointments table and added two links to accept and reject appointments. the links are displayed in every row of the table but when i click it the text accept & reject are only displayed in the first row & I also need to know how to insert the text that appears after the button click into the db i would request someone to pls provide me some help thanks!
<form method="post" action="delete.php" >
<table cellpadding="0" cellspacing="0" border="0" class="table table-condensed" id="example">
<thead>
<tr>
<th>appoinment ID</th>
<th>Date</th>
<th>time</th>
<th>teacher</th>
<th>parent</th>
<th> accept/reject </th>
<th>label</th>
</tr>
</thead>
<tbody>
<?php
$query=mysqli_query($conn, "select * from `app` left join `par` on par.par_id=app.par_id
left join `tea` on tea.tea_id=app.tea_id
ORDER BY app_id DESC");
if($query === false)
{
throw new Exception(mysql_error($conn));
}
while($row=mysqli_fetch_array($query))
{
$ann_id=$row['app_id'];
$date=$row['date'];
$msg=$row['time'];
$username = $row['username'];
$username = $row['p_username'];
?>
<tr>
<td><?php echo $row['app_id'] ?></td>
<td> <?php echo date('j/m/y',strtotime($row['date'])); ?></td>
<td><?php echo $row['time'] ?></td>
<td><?php echo $row['p_username'] ?></td>
<td><?php echo $row['username'] ?></td>
<td> reject
accept
</td>
<td>
<div id="chgtext">PENDING</div>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</form>
In jQuery it would look like this:
<td>
reject
accept
</td>
<td>
<div class="chgtext">PENDING</div>
</td>
Then, before closing body tag:
<script>
$(document).ready(function(){
$('.reject').on('click', function(){
var row = $(this).closest('tr'); //find the row the link is in
var thediv = row.find('.chgtext') //find the correct div within that tr
$(thediv).text('reject');
});
$('.accept').on('click', function(){
var row = $(this).closest('tr'); //find the row the link is in
var thediv = row.find('.chgtext') //find the correct div within that tr
$(thediv).text('accept');
});
});
</script>
You can make the code shorter, but I wanted to show you how it works step by step.

Keep checkboxes checked when the form is submitted

I have the following form with checkboxes.
<?php
include 'connection.php';
$sql="SELECT * FROM `tbl`";
$query=mysqli_query($connect,$sql);
echo "<table border='2px'>
<thead>
<th>ID</th>
<th>Title</th>
<th>Name</th>
<th>Doing</th>
<th>Done</th>
</thead>
<tbody>
<form method='POST'>";
while($res=mysqli_fetch_assoc($query)){
$id=$res['id'];
echo"<tr>
<td>{$res['id']}</td>
<td>{$res['title']}</td>
<td>{$res['name']}</td>
<td><input type='checkbox' name='doing[]' value='".$res['id'].$res['title'].$res['name']."'></td>
<td><input type='checkbox' name='done[]' value='".$res['id'].$res['title'].$res['name']."'></td>
</tr>";
}
echo "<input type='submit' value='OK' name='btn'>
</form>
</tbody>
</table>";
?>
How do I make the checkboxes keep their checked state when the form is submitted?
I assume that you don't want both doing and done to be checked at the same time, so I replaced the checkboxes with radio buttons because that is their intended behavior.
I changed the names and values for the radio buttons so that they can be easily accessed in PHP, and from the code you've supplied it doesn't look appear as if you're using the names and values afterwards anyways.
I cleaned up the markup and script layout to make it more readable.
Please let me know if I have deviated too far from the intent of your original code.
Note: This will display the posted values, but it will not save those values to the database.
(Demo)
<?php
include('connection.php');
$sql = "SELECT * FROM `tbl`";
$query = mysqli_query($connect,$sql);
function get_checked ( $id ) {
if ( isset($_POST) && isset($_POST['checked'][$id]) ) {
return $_POST['checked'][$id];
}
return false;
}
?>
<form method="post">
<table border="2px">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Name</th>
<th>Doing</th>
<th>Done</th>
</tr>
</thead>
<tbody>
<?php while ( $res = mysqli_fetch_assoc ( $query ) ): ?>
<?php $checked = get_checked ( $res['id'] ) ?>
<tr>
<td><?= $res['id'] ?></td>
<td><?= $res['title'] ?></td>
<td><?= $res['name'] ?></td>
<td><input type="radio" name="checked[<?= $res['id'] ?>]" value="doing" <?= $checked === "doing" ? 'checked' : '' ?>></td>
<td><input type="radio" name="checked[<?= $res['id'] ?>]" value="done" <?= $checked === "done" ? 'checked' : '' ?>></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
<input type='submit' value='OK' name='btn'>
</form>
You can try to use this code.Hope this will work (Also try to use mysqli or PDO):
<?php
include 'connection.php';
$sql="SELECT * FROM `tbl`";
$query=mysqli_query($connect,$sql);
echo "<table border='2px'>
<thead>
<th>ID</th>
<th>Title</th>
<th>Name</th>
<th>Doing</th>
<th>Done</th>
</thead>";
echo "<form method='POST'>";
echo "<tr>";
$s=0;
while($res=mysqli_fetch_assoc($query)){
$id=$res['id'];
$doing_v="";
$done_v="";
$c_doing="";
$c_done="";
if(isset($_POST['doing'][$s])){
$doing_v=$_POST['doing'][$s];
}
if(isset($_POST['done'][$s])){
$done_v=$_POST['done'][$s];
}
if($doing_v=='".$res['id'].$res['title'].$res['name']."'){
$c_doing="checked";
}
if($done_v=='".$res['id'].$res['title'].$res['name']."'){
$c_done="checked";
}
echo" <td>{$res['id']}</td>
<td>{$res['title']}</td>
<td>{$res['name']}</td>
<td><input type='checkbox' name='doing[]'
value='".$res['id'].$res['title'].$res['name']."' ".$c_doing." ></td>
<td><input type='checkbox' name='done[]'
value='".$res['id'].$res['title'].$res['name']."' ".$c_done." ></td>
</tr>";
$s++;
}
echo "</table>";
echo "<input type='submit' value='OK' name='btn'>";
echo "</form>";
?>

How to get value table row value using jquery/ajax

<?php
include "config.php";
// Fetch the data
$con = mysql_query("select * from product");
?>
<div style=" height:250px; overflow:auto;">
<table class="table table-striped table-bordered dTableR" id="ajxtable">
<tr>
<th>Jobno</th>
<th>Product</th>
<th>Qty</th>
<th>Designed by</th>
<th>Action</th>
</tr>
<?php
while ($row = mysql_fetch_array($con)) {
$id = $row['id'];
$pcode = $row['pcode'];
$lproduct = $row['lproduct'];
$mrprate = $row['mrprate'];
?>
<tr>
<td><?php echo $id; ?></td>
<td><?php echo $lproduct; ?></td>
<td><?php echo $mrprate; ?></td>
<td><?php echo "admin"; ?></td>
<td><input type="button" id="addmorePOIbutton1" style="width:25px;" value="+" onClick=""/>
<input type="button" id="delPOIbutton1" style="width:25px;" value="-" onClick=""/></td>
</tr>
<?php
}
?>
</table>
</div>
This is ajax page. Below table is auto refreshed every 5 seconds.
My doubt is how to get that particular row value.
When i click table row + button, get these particular row values, and place to index page text box and this '+' button also hide.
Kindly suggest any jquery or ajax code for adding below code.
I am new to jquery ,,anybody help me with sample code..that would help me greately. Thanks in advance
$(document).ready(function () {
$('#yourtablename tr').click(function (event) {
alert($(this).attr('id')); //trying to alert id of the clicked row
});
});
Above code may be help you and another solution is:
$('td').click(function(){
var row_index = $(this).parent().index();
var col_index = $(this).index();
});

Categories