How to retrieve info from a PHP-dynamically-generated-table with Js - javascript

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();
}
})
})

Related

Check if data updated_at 24 hours ago OR a day ago (laravel)

I am able to get days ago for each row in dattable using carbon. (view CustomController.php)
But before the user is able to edit the data. I want to check if the data is updated a day ago or 24 hours ago.
if 24 hours or a day passed user can't update the data if it is within 24 hours range then the user can update the data
Migration
public function up()
{
Schema::create('table_sessions', function (Blueprint $table) {
$table->id();
$table->string('session')->unique();
$table->timestamps();
});
}
CustomController.php
public function EditSession(Request $request)
{
$id = $request->id;
$session = SessionModel::find($id);
return response()->json($session);
}
public function FetchSession()
{
$session = SessionModel::all();
$output = '';
if ($session->count() > 0) {
$output .= '<table class="table text-center align-middle table-flush table-hover">
<thead class="thead-light">
<tr>
<th width="50px"><input type="checkbox" class="chk" name="main_checkbox" id="master"></th>
<th width="10%">ID</th>
<th>Session</th>
<th width="50%">Action</th>
<th>Updated On</th>
</tr>
</thead>
<tbody>';
foreach ($session as $session) {
$output .= '<tr>
<td><input type="checkbox" id="sub_master" name="session_checkbox" class="sub_chk" data-id="' . $session->id . '"></td>
<td>' . $session->id . '</td>
<td>' . $session->session . '</td>
<td>
<i class="bi-pencil-square h4"></i>
<!-- Edit Button -->
<i class="bi-trash h4"></i>
</td>
<td scope="row">
<label id="timeLabel">' . $session->updated_at->diffInDays(Carbon::now()) . ' days ago</label>
<!-- **getting days ago using this code** -->
</td>
</tr>';
}
$output .= '</tbody></table>';
echo $output;
} else {
echo '<h1 class="text-center text-shifondary my-5">No record present in the database!</h1>';
}
}
Web.php
Route::get('fetch-sessions', [CustomController::class, 'FetchSession'])->name('session.fetch.route');
Route::get('edit-session', [CustomController::class, 'EditSession'])->name('session.edit.route');
view.blade.php
<div class="table-responsive p-3" id="show_all_sessions">
</div>
{{-- edit Modal --}}
<div class="modal-body">
<form action="#" autocomplete="off" method="POST" id="edit_session_form" enctype="multipart/form-data">
#csrf
<input type="hidden" name="session_id" id="session_id">
<input type="" name="session_time" id="session_time">
<div class="form-group">
<label for="session">Session <span class="text-danger">*</span></label>
<div class="controls">
<input id="session_i" name="session_i" required class="form-control" placeholder="Enter Session Name">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-danger mb-1" data-dismiss="modal">Cancel</button>
<button type="submit" id="edit_session_btn" class="btn btn-secondary mb-1">Update</button>
</div>
</form>
</div>
{{-- //Scripts --}}
<script type="text/javascript">
$(document).ready(function() {
function fetchAllSessions() {
var _url = '{{ route("session.fetch.rn") }}';
$.ajax({
url: _url,
method: 'get',
success: function(response) {
$("#show_all_sessions").html(response);
$("table").DataTable();
}
});
}
// edit session ajax request for edit button on datatable
$(document).on('click', '.editIcon', function(e) {
e.preventDefault();
let id = $(this).attr('id');
//let time = $("#timeLabel").attr('text');
var _url = '{{ route("session.edit.route") }}';
$.ajax({
url: _url,
method: 'get',
data: {
id: id,
_token: '{{ csrf_token() }}'
},
success: function(response) {
// here some logic tocheck if clicked data updated 24 hours ago or a day ago using if else.
$("#session_id").val(response.id);
$("#session_i").val(response.session);
}
});
});
});
</script>
DataTable looks like this
Since you are rendering table in controller,so you can use ternary operator to dynamically load class name based on condition
<a href="#" id="' . $session->id . '" class="text-success mx-1 editIcon '.( $session->created_at->diffInHours(now())>24?"disable-link":null).'" data-toggle="modal" data-target="#editSessionModal">
i suggest you to move html content from controller to blade so you can easily use blade syntax
<i class="bi-pencil-square h4"></i>

Making a jQuery change permanent on page refresh

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>

TD contenteditable and update value in database

I have a table which i make the td's contenteditable, for the user to easily input the data needed.
Every rows and td have value of null in database. It will have value when the user will input something and it will save/update when button save is click
my php for tbody :
<?php
$emp_name = $_SESSION["emp_name"];
$month = $_SESSION["month"];
$REMARKS = $_SESSION[""];
$date_now = date('m');
$current_day = date('d');
$sample_var= $_SESSION["username"] ;
try {
$pdo = new PDO('mysql:host=localhost:3306;dbname=******;', '****', '*****' );
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $pdo->prepare(
" SELECT * from tbl_assessment WHERE employeeName = '{$_SESSION['emp_name']}' "
);
$flag = $stmt->execute();
if ( !$flag ) {
$info = $stmt->errorInfo();
exit( $info[2] );
}
while ( $row = $stmt->fetch( PDO::FETCH_ASSOC ) ) {
#$tbody1 .='<tr>';
$tbody1 .=' <input type="hidden" id="id" value="'.$_SESSION['id'].'"/> ';
$tbody1 .=' <input type="hidden" id="emp_name" value="'.$_SESSION['emp_name'].'"/> ';
$tbody1 .=' <input type="hidden" id="teamCode" value="'.$_SESSION['teamCode'].'"/> ';
$tbody1 .=' <input type="hidden" id="sectionCode" value="'.$_SESSION['sectionCode'].'"/> ';
$tbody1 .='<td style="height:30px" contenteditable>'.$row["date"].'</td>';
$tbody1 .='<td style="height:30px" contenteditable>'.$row["staffName"].'</td>';
$tbody1 .='<td style="height:30px" contenteditable>'.$row["findings"].'</td>';
$tbody1 .='<td style="height:30px" contenteditable>'.$row["action"].'</td>';
$tbody1 .='<td style="height:30px" contenteditable>'.$row["date_accomplished"].'</td>';
$tbody1 .='<td><button class="btn btn-warning px-2" id="btnSaveFindings" style="color:black;font-weight:bold;" title="Save"><i class="fas fa-save" aria-hidden="true"></i></button><button class="btn btn-info px-2" id="btnEdit" style="color:black;font-weight:bold;" title="Edit"><i class="fas fa-edit" aria-hidden="true"></i></button></td>';
#$tbody .='</tr>';
}
}
catch ( PDOException $e ) {
echo $e->getMessage();
$pdo = null;
}
?>
my html for table :
<div id="containerDiv" style="background-color:white;border-bottom:3px solid #ff6600;margin-left:50px;margin-right:50px;margin-bottom:140px;" class="animated fadeInUp">
<div class="" style="margin-left:15px;margin-right:15px;overflow-x:auto;" ><br>
<button class="btn btn-default px-3" style="float:right;" id="btnAddRow" name="btnAddRow" title="Add New row"><i class="fas fa-plus" aria-hidden="true"></i></button>
<table class="assessment" id="assessment" width="1526px" >
<thead style="background:-moz-linear-gradient( white, gray);">
<tr>
<th colspan="6" style="font-size:20px;">ASSESSMENT/FINDINGS:</th>
</tr>
<tr> <!---FIRST TABLE ROW--->
<th>DATE</th>
<th>NAME OF THE STAFF/S</th>
<th>ASSESSMENT/FINDINGS</th>
<th>ACTION TAKEN</th>
<th>DATE ACCOMPLISHED</th>
<th>ACTION</th>
</tr>
<tbody>
<?php echo $tbody1; ?>
</tbody>
</thead>
</table><br><br>
</div>
what would be the function of btnSaveFindings to update the value of td in database?
A few things to note,
Your query is not using a prepared statement - which is very simple with PDO; suggest you use that!
Your loop can generate multiple HTML elements with the same ID - this violates the uniqueness of an ID - if something can have the same ID, it can probably be a class instead.
When printing large blocks of HTML, its often better to exit PHP mode to print it where you need it.
To update the table, use jQuery with AJAX - assign classes to the different <td> elements, so we can fetch them with jQuery, and when you click the button, find the closest values of that row. Add a rows unique identifier to a data-* attribute of the button, so we know which row to update.
<?php
$emp_name = $_SESSION["emp_name"];
$month = $_SESSION["month"];
$REMARKS = $_SESSION[""];
$date_now = date('m');
$current_day = date('d');
$sample_var = $_SESSION["username"] ;
try {
$pdo = new PDO('mysql:host=localhost:3306;dbname=******;charset=utf8mb4', '****', '*****' );
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $pdo->prepare("SELECT * FROM tbl_assessment WHERE employeeName = :employeeName");
$stmt->execute(['employeeName' => $_SESSION['emp_name']]);
?>
<script>
$(".btnSaveFindings").on("click", function() {
var id = $(this).data('assessment-id'),
row = $(this).closest("tr"),
date = $(row).find('.assessment-date')[0],
staffname = $(row).find('.assessment-staffname')[0],
findings = $(row).find('.assessment-findings')[0],
action = $(row).find('.assessment-action')[0],
accomplished = $(row).find('.assessment-date-accomplished')[0];
$.ajax({
type: "POST",
url: "updateRow.php",
data: {id: id,
date: date,
staffname: staffname,
findings: findings,
action: action,
accomplished: accomplished},
success: function(data) {
var status = data.status,
message = data.message;
alert(message);
}
});
});
</script>
<div id="containerDiv" style="background-color:white;border-bottom:3px solid #ff6600;margin-left:50px;margin-right:50px;margin-bottom:140px;" class="animated fadeInUp">
<div class="" style="margin-left:15px;margin-right:15px;overflow-x:auto;" ><br>
<button class="btn btn-default px-3" style="float:right;" id="btnAddRow" name="btnAddRow" title="Add New row"><i class="fas fa-plus" aria-hidden="true"></i></button>
<table class="assessment" id="assessment" width="1526px" >
<thead style="background:-moz-linear-gradient( white, gray);">
<tr>
<th colspan="6" style="font-size:20px;">ASSESSMENT/FINDINGS:</th>
</tr>
<tr> <!---FIRST TABLE ROW--->
<th>DATE</th>
<th>NAME OF THE STAFF/S</th>
<th>ASSESSMENT/FINDINGS</th>
<th>ACTION TAKEN</th>
<th>DATE ACCOMPLISHED</th>
<th>ACTION</th>
</tr>
<tbody>
<?php
while ($row = $stmt->fetch()) { ?>
<tr>
<td style="height:30px" class="assessment-date" contenteditable><?php echo $row["date"] ?></td>
<td style="height:30px" class="assessment-staffname" contenteditable><?php echo $row["staffName"]; ?></td>
<td style="height:30px" class="assessment-findings" contenteditable><?php echo $row["findings"]; ?></td>
<td style="height:30px" class="assessment-action" contenteditable><?php echo $row["action"]; ?></td>
<td style="height:30px" class="assessment-date-accomplished" contenteditable><?php echo $row["date_accomplished"]; ?></td>
<td>
<button class="btn btn-warning px-2 btnSaveFindings" style="color:black;font-weight:bold;" title="Save" data-assessment-id="<?php echo $row['id']; ?>">
<i class="fas fa-save" aria-hidden="true"></i>
</button>
<button class="btn btn-info px-2 btnEdit" style="color:black;font-weight:bold;" title="Edit">
<i class="fas fa-edit" aria-hidden="true"></i>
</button>
</td>
</tr>
<?php
}
?>
</tbody>
</thead>
</table>
<br />
<br />
</div>
<?php
} catch(PDOException $e) {
error_log($e->getMessage());
echo "An error occurred";
}
Then you need to create the file updateRow.php that runs the query.
<?php
header('Content-Type: application/json');
$pdo = new PDO('mysql:host=localhost:3306;dbname=******;charset=utf8mb4', '****', '*****' );
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
// See that the POST is sent
if (empty($_POST)) {
echo json_encode(['status' = false, 'message' => 'No data was sent. Update aborted']);
exit;
}
try {
$stmt = $pdo->prepare("UPDATE tbl_assessment
SET date = :date,
staffName = :staffName,
findings = :findings,
action = :action,
date_accomplished = :date_accomplished
WHERE id = :id");
$stmt->execute(['date' => $_POST['date'],
'staffName' => $_POST['staffName'],
'findings ' => $_POST['findings'],
'action ' => $_POST['action'],
'date_accomplished ' => $_POST['date_accomplished'],
'id ' => $_POST['id']]);
echo json_encode(['status' = true, 'message' => 'Update completed.']);
} catch (PDOException $e) {
error_log($e->getMessage());
echo json_encode(['status' = false, 'message' => 'An error occurred. Update failed.']);
}
As a final note, its often way better to use CSS classes on elements instead of inline styling. Makes for cleaner code, and more repeatable code.

I am getting same value of every button

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 );
}
});
}

Jquery 2.1 - On click is stacking calls

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.

Categories

Resources