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 );
}
});
}
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!");
}
}
Back Ground:
I have made a script that loads a table of product names, when you click a button on that table row it shows a search box. This search box uses the jquery UI autocomplete function. When an option is selected it pulls that products information from a different database from this main project database and puts them in their corresponding tags within the table. It also then submits this content to another table in another database which is the main database for the project. It is storing the information correctly, and when the foreach loop runs with the database content from the main project it is loading correctly. The button that the user presses to reveal the search box says "Link Product", once they selected it the button changes css and html value to Edit Product.
The problem
The issue I'm having is any table row that has content loaded from the main database needs to have the "Edit Button" still be there and any blank rows must show the Link Product Button. But when you refresh the page they all revert to "Link Button".
Now I'm going to show you the code but I will give you a heads up its very messy as I'm new to both ajax and jquery.
The Code
Html Page
<div class="container">
<div class="row">
<div class="col text-center">
<h3 id="edit_sheet_title" class="mt-3 mb-3"><?php echo $title; ?></h3>
</div>
</div>
<div class="row mb-5">
<div class="col-xl-12 col-md-12 col-sm-12 col-12 text-center">
Bulk Import
Container Import
Add Product
Generate Sheet
Go Back
</div>
</div>
</div>
<div class="table-container">
<div class="row">
<div class="col">
<div class="table-responsive">
<table class="table" id="sheet_list">
<thead>
<tr>
<th class="align-middle th-id">ID</th>
<th class="align-middle th-name">Product Name</th>
<th>Ingredients</th>
<th id="button_th"></th>
</tr>
</thead>
<tbody>
<?php if(!empty($sheet_product_list)) { ?>
<?php foreach($sheet_product_list as $product) { ?>
<tr>
<td><p data-id="entry_id" id="entry_id" class="table-p"><?php echo $product['entry_id']; ?></p></td>
<td class="td-name"><?php echo $product['display_name']; ?></td>
<td>
<div id="search_div">
<input type="text" class="wholesale_product_search mb-5 block" data-info="search_box" data-entry-id="<?php echo $product['entry_id']; ?>" name="product_search" id="product_search" placeholder="Search for product...">
</div>
<p data-info="product_id" id="product_id" class="<?php echo $product['entry_id']; ?>">
<?php if(isset($product['wholesale_product_id'])){ echo "Product ID: " . $product['wholesale_product_id'];} ?>
</p>
<p data-info="wholesale_name" id="wholesale_name" class="<?php echo $product['entry_id']; ?>">
<?php if(isset($product['wholesale_name'])){ echo $product['wholesale_name'];} ?>
</p>
<p data-info="is_manual" class="<?php echo $product['entry_id']; ?>">
</p>
<p data-info="ingredients_section" id="ingredients_section" class="<?php echo $product['entry_id']; ?>">
<?php if(isset($product['wholesale_ingredients'])){echo $product['wholesale_ingredients'];} ?>
</p>
</td>
<td class="pull-right align-middle">
<div class="button_td_div">
<button id="edit_product_button" data-id="<?php echo $product['entry_id']; ?>" class="btn btn-info" role="button">Link Product</button><br>
<a id="column_button" href="<?php echo URLROOT; ?>product/delete/<?php echo $sheet['sheet_id']; ?>/<?php echo $product['entry_id']; ?>" class="btn btn-danger" role="button">Delete Product</a>
</div>
</td>
</tr>
<?php } ?>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<input type="hidden" id="sheet_id" value="<?php echo $sheet_id; ?>">
Jquery Function
$('button[data-id]').click( function () {
var display_name = $('.td-name').html();
var entry_id = $(this).attr("data-id");
var search_box = $("input[data-info='search_box'][data-entry-id="+entry_id+"]");
var ingredients_section = $("p[data-info='ingredients_section']."+entry_id);
var wholesale_name = $("p[data-info='wholesale_name']."+entry_id);
var wholesale_product_id = $("p[data-info='product_id']."+entry_id);
var edit_button = $('button[data-id='+entry_id+']');
const sheet_id = $('#sheet_id').val();
$(search_box).on( "autocompleteselect", function(e, ui) {
var result_string = ui.item.value; // this is the string returned from the search
var product_id = result_string.match( /\d+/ )[0];
$(search_box).hide();
edit_button.html('Edit Product');
edit_button.removeClass("btn btn-warning").addClass("btn btn-success");
$.ajax({
type: "GET",
url: ajax_url,
data: "product_id="+product_id,
success: function(data){
var obj = JSON.parse(data);
const ingredients = obj[0].ingredients;
const product_name = obj[0].name;
const w_product_id = obj[0].product_id;
$(wholesale_product_id).html('Product ID: '+w_product_id);
$('#confirmed').show();
$(wholesale_name).html('Wholesale Name: '+product_name);
$(ingredients_section).html(ingredients);
$.ajax({
type: "POST",
url: ajax_url,
data: {post_sheet_id: sheet_id,post_wholesale_product_id: w_product_id, post_wholesale_ingredients: ingredients, entry_id: entry_id,wholesale_product_name: product_name},
success: function(data){
var obj = JSON.parse(data);
$.ajax({
type: "GET",
url: ajax_url,
data: "sheet_id="+sheet_id+"&content",
success: function(data){
var obj = JSON.parse(data);
const content = obj[0].wholesale_product_id;
console.log(content);
}
});
}
});
}
});
} );
if($(this).html() == 'Link Product'){
$(search_box).show();
$(search_box).focus();
$(this).html('Cancel');
$(this).removeClass("btn btn-info");
$(this).addClass("btn btn-warning");
} else if($(this).html() == 'Cancel'){
$(search_box).hide();
$(this).removeClass("btn btn-warning");
$(this).addClass("btn btn-info");
$(this).html('Link Product');
}
} );
$(function() {
$(".wholesale_product_search").autocomplete({
source: ajax_url,
minLength: 1
});
});
I have not a single clue how to make the Edit Product html value to stay on the page refresh, every time I refresh that page all the buttons go back to saying Link Product, but I only want blank ingredients boxes to have a "Link Product" button, any with ingredients loaded the button needs to say "Edit Product".
I have been driven mad by this for days and I'm at my whits end.
Any help, literally anything at all would spare me my sanity.
** EDIT **
I know its a horrendous mess, but my deadline is fast approaching I'm miles off and at this point will do whatever it takes to make it work. It's used in house and is not accessible to the outside world.
Just use php if else statmant:
<?= isset($product['wholesale_ingredients']) ? 'Edit product' : 'Link Product' ?>
This will echo 'Edit product' if wholesale_ingredients is set, and 'Link product' wholesale_ingredients is empty
This is how your actual button should look like
<div class="button_td_div">
<button id="edit_product_button" data-id="<?php echo $product['entry_id']; ?>" class="btn btn-info" role="button">
<?= isset($product['wholesale_ingredients']) ? 'Edit product' : 'Link Product' ?>
</button><br>
<a id="column_button" href="<?php echo URLROOT; ?>product/delete/<?php echo $sheet['sheet_id']; ?>/<?php echo $product['entry_id']; ?>" class="btn btn-danger" role="button">Delete Product</a>
</div>
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 used $_POST to get the value of order_id but it didn't quiet get right away. I need first to click Button "Show Food" or any button (As seen in the photo below) to popup the table I want to output. And I tried using if(isset($_SESSION['viewOrder'])) to get the value of button in order.php but it didn't get it in ordermodal even I use SESSION. How can I get the value of button viewOrder?
if I change the WHERE order_id=$order_id to WHERE order_id=724 it will popup right away the value of that number (724) BUT it is the output of ALL my order in the food table. So my problem is how can I output the right output for specific order_id?
Example I have 2 order order_id 1 and order_id 2, the value of 1 is burger and pizza and the value of 2 is salad and sandwich , So when I click order_id 1(View Order button in order.php) the value of that food table is burger and pizza only and then when I click the order_id 2 (View Order button in order.php) the value should be salad and sandwich not burger and pizza.
I hope you understand my explanation and I hope for your help guys, I really need to solve this right away. I stacked at this problem couple of days already. Really appreciate your help guys. Big Thanks!
This is my error
This is what I get when clicking a button inside the ordermodal.php
This is my code for order.php .
<button type="button"
<?php if($order['order_status'] == 'Dispatched'){ ?> input style="background-color:#ffff00;color:black"
<?php } else if($order['order_status'] == 'Accepted'){ ?> input style="background-color:#0000ff;color:white" <?php } else if($order['order_status'] == 'Pending'){ ?> input style="background-color:#B0C4DE;color:black" { <?php } ?>
class="btn btn-success" data-toggle="modal" data-target="#myModal" onclick="viewOrder( '<?= $order['order_id'] ?>', '<?= $order['order_id'] ?>', '<?= $order['user_id'] ?>', '<?= $date ?>', '<?= $time ?>', '<?= $order['order_deliveryCharge'] ?>', '<?= $order['order_totalAmount'] ?>', '<?= $order['address'] ?>', '<?= $order['coordinates'] ?>', '<?= $order['driver_number'] ?>', '<?= $order['order_status'] ?>')"> View Order </button>
<script>
function viewOrder(order_id, order_id, user_id, order_date, order_time, order_deliveryCharge, order_totalAmount, address, coordinates, driver_number, order_status) {
document.getElementById("titleModal").innerHTML = "Order Information";
document.getElementsByName("ORDER_ID")[0].setAttribute("value", order_id);
document.getElementsByName("ORDER_ID_MODAL_2")[0].setAttribute("value", order_id);
document.getElementsByName("user_id")[0].setAttribute("value", user_id);
document.getElementsByName("order_date")[0].setAttribute("value", order_date);
document.getElementsByName("order_time")[0].setAttribute("value", order_time);
document.getElementsByName("order_deliveryCharge")[0].setAttribute("value", order_deliveryCharge);
document.getElementsByName("order_totalAmount")[0].setAttribute("value", order_totalAmount);
document.getElementsByName("address")[0].setAttribute("value", address);
document.getElementsByName("coordinates")[0].setAttribute("value", coordinates);
document.getElementsByName("drivers_number")[0].setAttribute("value", driver_number);
document.getElementsByName("order_status")[0].setAttribute("value", order_status);
document.getElementsByName("viewOrder")[0].setAttribute("name", "viewOrder");
}
</script>
And this is my code for ordermodal.php
<div class="form-group">
<label for="order_id" class="col-sm-2 control-label">Order ID</label>
<div class="col-lg-3">
<input type="text" input style="width:500px" class="form-control" name="ORDER_ID" id="ORDER_ID" placeholder="" value="" required="required" readonly>
</div>
</div>
<?php
if(isset($_POST['ORDER_ID'])){
$order_id = trim(addslashes($_POST['ORDER_ID']));
$sql = "SELECT food_name, special_request, quantity, amount
FROM cart_tbl
WHERE order_id=$order_id";
$result = mysqli_query(connection2(), $sql);}
?>
<table class="table table-hover table-bordered">
<thead>
<tr>
<th>Food</th>
<th>Special Request</th>
<th>Quantity</th>
<th>Amount</th>
</tr>
</thead>
<?php
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $row["food_name"];?></td>
<td><?php echo $row["special_request"];?></td>
<td><?php echo $row["quantity"];?></td>
<td><?php echo $row["amount"];?></td>
</tr>
<?php
}
}
?>
</table>
</div>
<div class="modal-footer">
<button type="submit" input style="background-color:##FF0000;color:white;float:left" name="showFood" id="showFood" class="btn btn-primary " onclick="if(!confirm('Are you sure you want to see food order?')){return false;}" > Show Food</button>
<button type="submit" input style="background-color:#4CAF50;color:white" name="submitDelivered" id="submitDelivered" class="btn btn-primary " onclick="if(!confirm('Are you sure you want to deliver order?')){return false;}" > Delivered </button>
<button type="submit" input style="background-color:#0000FF;color:white" name="submitAccept" id="submitAccept" class="btn btn-primary" onclick="if(!confirm('Are you sure you want to accept order?')){return false;}"> Accept </button>
<button type="button" style="background-color:#FFFF00;color:black" class="btn btn-success" data-toggle="modal" data-target="#myDropdown"> Send </button>
<button type="submit" input style="background-color:#f44336;color:white" name="submitCancel" class="btn btn-danger" onclick="if(!confirm('Are you sure you want to cancel order?')){return false;}">Cancel</button>
Change this line
document.getElementsByName("ORDER_ID")[0].setAttribute("value", order_id);
To
document.getElementsByName("ORDER_ID")[1].setAttribute("value", order_id);
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.