I have a strange bug with on click event. Every time I click on button it is adding one more post call. If I click update button once it will do one post call, if I click it again (for the second time) it will make two post calls and so one. The code it self is working, but this bug is a bit annoying. Does anyone have idea what is going one?
var
editCutomerType = $('a[role=editCutomerType]'),
deleteCutomerType = $('a[role=deleteCutomerType]');
editCutomerType.on('click', function(e) {
var
$this = $(this),
parentContainer = $this.closest('.parent'),
nameContainer = parentContainer.find('.name'),
update = $this.next('a'),
cancel = update.next('a'),
oldName = nameContainer.text()
i = 0;
$this.hide();
update.removeClass('hidden');
cancel.removeClass('hidden');
nameContainer.empty().append('<input type=text name=name value="' + oldName + '">');
update.on('click', function(e) {
var
url = $(this).attr('href'),
newName = parentContainer.find('input').val(),
data = 'name=' + newName;
$.post(url, data, function(data, textStatus, xhr) {
nameContainer.empty().text(newName);
$this.show();
update.addClass('hidden');
cancel.addClass('hidden');
});
return false;
});
cancel.on('click', function(e) {
nameContainer.empty().text(oldName);
$this.show();
update.addClass('hidden');
cancel.addClass('hidden');
return false;
});
i++;
console.log(i);
return false;
});
HTML code:
<div class="col-md-7">
<div class="panel panel-dark panel-light-green">
<div class="panel-heading">
<span class="panel-title"><i class="panel-title-icon fa fa-smile-o"></i>Customer Types</span>
</div> <!-- / .panel-heading -->
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th></th>
</tr>
</thead>
<tbody class="valign-middle">
<?php
$i = 1;
foreach ($customerTypes as $ct): ?>
<tr class="parent">
<td><?php echo $i ?></td>
<td class="name"><?php echo $ct['name'] ?></td>
<td>
<a role="editCutomerType" class="btn btn-primary btn-xs">Edit</a>
<a class="btn btn-primary btn-xs hidden" href="<?php echo base_url("customerTypes/save/{$ct['id']}") ?>">Update</a>
<a role="cancel" class="btn btn-warning btn-xs hidden">Cancel</a>
<a role="deleteCutomerType" class="btn btn-danger btn-xs" href="<?php echo base_url("customerTypes/delete/{$ct['id']}") ?>">Delete</a>
</td>
<td></td>
</tr>
<?php $i++; endforeach ?>
</tbody>
</table>
</div> <!-- / .panel -->
</div>
Give your update link a role like your other buttons:
foreach ($customerTypes as $ct): ?>
<tr class="parent">
<td><?php echo $i ?></td>
<td class="name"><?php echo $ct['name'] ?></td>
<td>
<a role="editCutomerType" class="btn btn-primary btn-xs">Edit</a>
<a role="update" class="btn btn-primary btn-xs hidden" href="<?php echo base_url("customerTypes/save/{$ct['id']}") ?>">Update</a>
<a role="cancel" class="btn btn-warning btn-xs hidden">Cancel</a>
<a role="deleteCutomerType" class="btn btn-danger btn-xs" href="<?php echo base_url("customerTypes/delete/{$ct['id']}") ?>">Delete</a>
</td>
<td></td>
</tr>
<?php $i++; endforeach ?>
Then you can bind handlers for update and cancel outside the editCutomerType handler:
$("a[role=update]").on('click', function(e) {
var
$this = $(this),
cancel = $this.next('a'),
edit = $this.prev('a'),
url = $this.attr('href'),
newName = $this.closest('.parent').find('input').val(),
nameContainer = parentContainer.find('.name'),
data = 'name=' + newName;
$.post(url, data, function(data, textStatus, xhr) {
nameContainer.empty().text(newName);
edit.show();
$this.addClass('hidden');
cancel.addClass('hidden');
});
return false;
});
You can do the cancel button similarly.
To stop the handler from being executed more than once, add stopImmediatePropagation() to the function.
update.on('click', function(e) {
var
url = $(this).attr('href'),
newName = parentContainer.find('input').val(),
data = 'name=' + newName;
$.post(url, data, function(data, textStatus, xhr) {
nameContainer.empty().text(newName);
$this.show();
update.addClass('hidden');
cancel.addClass('hidden');
});
return false;
e.stopImmediatePropagation();
});
To remove the old handler, you can call update.off('click').on('click', ...
Do the same for the cancel event.
Sent from phone, so sorry for not being verbose.
Related
I have the following ajax that needs to pass the userID to a PHP script.
document.getElementById("delete").addEventListener("click", function(){
if (confirm("Are you sure you want to delete this user's account?")) {
$.ajax({
url: 'deleteUser.php?id='+<?php echo $userID ?>,
success: function(data) {
toastr.danger("User successfully deleted!");
}
});
} else {
}
});
I'm unsure how to actually get the row data from the button used since they're posted in the TD of each row as it goes through each record in the set. How would one accomplish this?
<table class="table table-bordered">
<thead class="thead-dark">
<tr>
<th scope="col">First Name</th>
<th scope="col">Last Name</th>
<th scope="col">Email</th>
<th scope="col">Username</th>
<th scope="col">Account Type</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
<?php
$query = $pdo->query("SELECT * FROM accounts WHERE company ='".$res['company']."' ")->fetchall();
foreach($query as $row){
echo ' <tr>';
echo ' <td>'.$row['fname'].'</td>' ;
echo ' <td>'.$row['lname'].'</td>' ;
echo ' <td>'.$row['email'].'</td>' ;
echo ' <td>'.$row['account_name'].'</td>' ;
echo ' <td>'.$row['user_type'].'</td>' ;
echo ' <td><button id="delete" type="button" class="btn btn-danger"><i class="far fa-trash-alt"></i></button>';
echo ' <button id="edit" type="button" class="btn btn-info"><i class="fas fa-user-edit"></i></button> </td>';
echo ' </tr>';
}
?>
</tbody>
</table>
You can do it this way:
php:
foreach($query as $row){
echo ' <tr>';
echo ' <td>'.$row['fname'].'</td>' ;
echo ' <td>'.$row['lname'].'</td>' ;
echo ' <td>'.$row['email'].'</td>' ;
echo ' <td>'.$row['account_name'].'</td>' ;
echo ' <td>'.$row['user_type'].'</td>' ;
echo ' <td><button data-id="' . $row['id'] . '" type="button" class="btn btn-danger delete"><i class="far fa-trash-alt"></i></button>';
echo ' <button type="button" class="btn btn-info edit"><i class="fas fa-user-edit"></i></button> </td>';
echo ' </tr>';
}
Jquery:
$("button.delete").each(function(){
$(this).on('click', function(e){
if (confirm("Are you sure you want to delete this user's account?")) {
$.ajax({
url: 'deleteUser.php?id='+$(this).data('id'),
success: function(data) {
toastr.danger("User successfully deleted!");
}
});
} else {
//do something else
}
});
});
HTML 4.01 specification says ID must be document-wide unique.
HTML 5 specification says the same thing but in other words. It says that ID must be unique in its home subtree, which is basically the document if we read the definition of it.
I'd fix that first: <button id="delete" needs to be unique
Next - I'd add an onClick to your delete button so you have <button onclick="deleteUser(2);"
Then, I'd rewrite your listener registration to just be a function:
function deleteUser(id){
if (confirm("Are you sure you want to delete this user's account?")) {
$.ajax({
url: 'deleteUser.php?id='+<?php echo $userID ?>,
success: function(data) {
toastr.danger("User successfully deleted!");
}
}
i have fetch the data from database every thing work fine but problem is when i submit ajax request to test.php i got same value of every button
I am very week in Ajax and Java so please help me ,i am confuse how to get value of every button separately and submit to test.php file
<tbody>
<?php
$letter = mysqli_query($con,"SELECT * FROM letters order by id DESC");
if (mysqli_num_rows($letter) > 0) {
while ($rows_letter=mysqli_fetch_array($letter)) {
$id = $rows_letter['id'];
$subject = $rows_letter['subject'];
$status = $rows_letter['status'];
?>
<tr>
<th class="text-center" scope="row">1</th>
<td class="text-center"><?php echo $subject ;?></td>
<td class="text-center">
<?php
if ($status == 1) {
echo '<mark style="background-color: #5cb85c; color:white;"> Successfully Sent </mark>';
} else {
echo '<mark style="background-color:#f0ad4e; color:white;"> Not Sent Yet </mark>';
}
?>
</td>
<td>
<button type="button" class="btn btn-info btn-sm btn-block">
<span class="fa fa-pencil-square-o"></span> Edit</button>
</td>
<td>
<button type="button" class="btn btn-danger btn-sm btn-block">
<span class="fa fa-trash-o"></span> Move To Trash</button>
</td>
<td>
<button type="button" onclick="startsend();" id="id" value="<?php echo $id;?>"class="btn btn-success btn-sm btn-block">
<span class="fa fa-paper-plane-o"></span> Send To All</button>
</td>
</tr>
<?php
}
}
?>
</tbody>
<script type='text/javascript'>
//AJAX function
function startsend() {
var id = $('#id').val();
$.ajax({
type: "POST",
url: "test.php",
data:{ id: id
},
success: function(msg){
alert( "Button Id is " + msg );
}
});
}
</script>
and this is my test.php file
<?php
$id = $_POST['id']; echo $id;
//// rest of process according to id
?>
Try this, pass the id as param to ajax
Html:
<td><button type="button" onclick="startsend(<?php echo $id;?>);"
id="id" value="<?php echo $id;?>"class="btn btn-success btn-sm btn-block">
<span class="fa fa-paper-plane-o"></span> Send To All</button></td>
Ajax:
function startsend(id) {
$.ajax({
type: "POST",
url: "test.php",
data:{ id: id },
success: function(msg){
alert( "Button Id is " + msg );
}
});
}
I'm making some sort of commerce project, where in the cart page I'm displaying the products that the user have selected.
here is the code:
<div class="container-table-cart pos-relative">
<div class="wrap-table-shopping-cart bgwhite">
<table class="table-shopping-cart">
<tr class="table-head">
<th class="column-1"></th>
<th class="column-2">Prodotto</th>
<th class="column-3">Prezzo</th>
<th class="column-4 p-l-70">Quantità </th>
<th class="column-5">Totale</th>
</tr>
<?php
$subtotal = (float)0;
$priceConsegna = (float)1.50;
$total = (float)0;
if (!($showcart)) {
echo '<button onclick="logInRedirect()" class="flex-c-m size2 bg1 bo-rad-23 hov1 s-text1 trans-0-4">
Accedi Per Ordinare
</button>';
} else {
//echo "goodbye";
$orderArray = array();
$orderArray = $arrayValues;
foreach ($orderArray as $value) {
$productQty = $value;
$productName = key($orderArray);
$productImage = getImageFromName($productName);
$productPrice = getPriceFromName($productName);
// Formatting Price
$totalPrice = $productQty * $productPrice;
//echo $totalPrice;
$subtotal += $totalPrice;
//echo $subtotal;
?>
<tr id="" class="table-row">
<td class="column-1">
<div class="cart-img-product b-rad-4 o-f-hidden">
<img src="pizze/<?php echo $productImage; ?>" alt="IMG-PRODUCT">
</div>
</td>
<td id="product-name" class="column-2"><?php echo $productName; ?> </td>
<td class="column-3"><?php echo formatPrice($productPrice); ?></td>
<td class="column-4">
<div class="flex-w bo5 of-hidden w-size17">
<button onclick="manageQty('DwnProd')" class="btn-num-product-down color1 flex-c-m size7 bg8 eff2">
<i class="fs-12 fa fa-minus" aria-hidden="true"></i>
</button>
<input id="productQty" class="size8 m-text18 t-center num-product" type="number"
name="num-product1" value="<?php echo $productQty; ?>">
<button onclick="manageQty('UpProd')" class="btn-num-product-up color1 flex-c-m size7 bg8 eff2">
<i class="fs-12 fa fa-plus" aria-hidden="true"></i>
</button>
</div>
</td>
<td class="column-5">
<?php
echo formatPrice(number_format((float)$totalPrice, 2, '.', ''));
?>
</td>
</tr>
<?php
next($orderArray);
}
}
?>
</table>
</div>
</div>
Right now I'm in the process of let the user modify the quantity of a single product, I'm using JS and here is the code:
function manageQty(key){
var number = $('#productQty');
var name = $('#product-name')
number.val().replace(/\n/g, '');
number.val().replace(/\t/g, '');
name.text().replace(/\n/g, '');
name.text().replace(/\t/g, '');
$.ajax({
url: 'ajax.php',
method: 'POST',
dataType: 'text',
data:{
key: key,
name: name.text(),
qty: number.val()
}, success: function (response) {
console.log(response);
setCookie('phpcart', response,7);
UpdatetotalSub();
}
})
}
The issue here is that when i press the btn-product Up or the btn-product-down, I always modify the first element of the table... Not the one that I'm trying to modify!
My understanding is that I'm doing something wrong on the js side of things.
Let me know if there is an "easy-fix" thanks
Instead of using onClick attribute, I would use :
<button data-val="UpProd" id="myProdBtnn" class="btn-num-product-up color1 flex-c-m size7 bg8 eff2">
<i class="fs-12 fa fa-plus" aria-hidden="true"></i>
</button>
JS :
$('#myProdBtnn').on('click',function(){
var key=$(this).attr('data-val');
var number = $(this).closest('input [id="productQty"]'); //change this
var name = $(this).closest('td[id="product-name"]'); //change this
number.val().replace(/\n/g, '');
number.val().replace(/\t/g, '');
name.text().replace(/\n/g, '');
name.text().replace(/\t/g, '');
$.ajax({
url: 'ajax.php',
method: 'POST',
dataType: 'text',
data:{
key: key,
name: name.text(),
qty: number.val()
}, success: function (response) {
console.log(response);
setCookie('phpcart', response,7);
UpdatetotalSub();
}
})
})
I'm working with codeigniter, and i want to show the detail data in modal, the detail data is from another table.
I have a button like this:
<button class="btn btn-info" onclick="detail_barang("<?php echo $tbrang->id_barang;?>")">Detail</button>
And this is my detail_barang function:
function detail_barang(id)
{
$('#form')[0].reset(); // reset form on modals
$.ajax({
url : "<?php echo site_url('admin/Barang/barang/ajax_detail_barang/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('#modal_detail').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Detail Barang'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Kesalahan!');
}
});
}
Modal Script:
<div class="modal fade" id="modal_detail">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 class="modal-title">Detail Barang</h3>
</div>
<div class="modal-body">
<table class="table table-striped" id="tblGrid">
<thead id="tblHead">
<tr>
<th>ID Barang</th>
<th>No Inv</th>
<th class="text-right">Kondisi</th>
</tr>
</thead>
<tbody>
<?php
foreach($detail_barang as $detil)
{?>
<tr>
<td><?php echo $detil->id_barang ?></td>
<td><?php echo $detil->no_inv ?></td>
<td><?php echo $detil->kondisi ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default " data-dismiss="modal">Close</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
ajax_detail_barang function:
public function ajax_detail_barang($id)
{
$where = array
(
'id_barang' => $id,
'kondisi' => 'Ada'
);
$data['detail_barang'] = $this->modelku->get_by_id('detail_barang', $where)->result();
echo json_encode($data);
}
get_by_id function:
public function get_by_id($table, $where)
{
$this->db->from($table);
$this->db->where($where);
$query = $this->db->get();
return $query->row();
}
But when i click the button, the error appears "Kesalahan!" whats wrong my code?
The problem i see is in how u are using the returned data from ur model
public function get_by_id($table, $where)
{
$this->db->from($table);
$this->db->where($where);
$query = $this->db->get();
return $query->row();
//at this point it already contains the data u need
}
but here u are using result();
$data['detail_barang'] = $this->modelku->get_by_id('detail_barang', $where)->result();
//i tried and u cant use result method if u already executed row method.
In short, remove result()
Hope my answer helps u.
I have the following code to add, edit and delete user. Add function works fine but edit and delete functions are not working. I'm not sure where it goes wrong.
application/view/userlist.php
<script type="text/javascript">
var oTable;
$(document).ready(function()
{
oTable = $('#userListTable').dataTable( {
"iDisplayLength": 25,
"aLengthMenu": [5,10,25,50,100],
"aoColumns": [ {
"bSortable": false },
null,
null,
null,
null,
null,
null,
null,
null, {
"bSortable": false } ]
});
oTable.fnSort( [ [1,'asc'] ] );
});
function removeUser()
{
var ids = '';
$("input:checked", oTable.fnGetNodes()).each(function(){
if (ids == '') {
ids += $(this).val();
}else{
ids += ','+$(this).val();
}
});
var url = "<?php echo base_url(); ?>Admin/userRemove/";
var form = $('<form action="' + url + '" method="post">' +
'<input type="text" name="ids" value="' + ids + '" />' +
'</form>');
console.log(form);
$('body').append(form);
if (ids != '') {
form.submit();
}else{
alert('Select user to remove');
}
}
</script>
//some codes here
<button type="button" data-hover="tooltip" onclick="removeUser()" title="Delete Selected" class="btn btn-default">
<i class="fa fa-eraser"></i>
</button>
<button type="button" data-hover="tooltip" title="Add New User" class="btn btn-default">
<div class="panel-header" data-toggle="modal" data-target="#myModal">
<i class="fa fa-user-plus fa-1x"></i>
</div>
</button>
// #myModal codes here
<script type="text/javascript">
$(document).ready(function(){
$('.edit-row').live('click',function(){
var me = $(this);
var editModal = $('#myModalEdit');
editModal.find('#userID').val(me.attr('data-userID'));
editModal.find('#userName').val(me.attr('data-userName'));
editModal.find('#userFullName').val(me.attr('data-userFullName'));
editModal.find('#userPass').val(me.attr('data-userPass'));
editModal.find('#userEmail').val(me.attr('data-userEmail'));
$('#myModalEdit').modal('show');
});
});
</script>
//#myModalEdit codes here
<table id="userListTable" class="table table-hover table-striped table-bordered" >
<thead>
<tr>
<th><center><strong>#</strong></center></th>
<th><h4><strong>USER ID</strong></h4></th>
<th><h4><strong>FULL NAME</strong></h4></th>
<th><h4><strong>USERNAME</strong></h4></th>
<th><h4><strong>EMAIL</strong></h4></th>
</tr>
</thead>
<tbody>
<?php
if(!empty($data_user)):
foreach($data_user as $row)
{
echo '<tr>
<td class="text-center">
<input type="checkbox" name="selectAction" value="'.$row->userID.'" unchecked>
</td>';
echo '<td>'.$row->userID.'</td>';
?>
<td><a class="edit-row" href="javascript:"
data-userID="<?php echo $row->userID; ?>"
data-userFullName="<?php echo $row->userFullName; ?>"
data-userName="<?php echo $row->userName; ?>"
data-userEmail="<?php echo $row->userEmail; ?>"
>
<?php echo $row->userFullName; ?>
</a>
</td>
<?php
echo '<td>'.$row->userName.'</td>';
echo '<td>'.$row->userEmail.'</td>';
echo '</tr>';
}
endif;
?>
</tbody>
</thead>
</table>
// other codes
application/controllers/Admin.php
public function userRemove() {
$ids = $this->input->post('ids');
if (!empty($ids)) {
$this->db->where('userID IN (' . $this->input->post('ids') . ')')
->
delete('user_tbl', $data);
}
redirect('userlist', 'refresh');
}
Edit and delete functions seems not working..