TD contenteditable and update value in database - javascript

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.

Related

Wht is wrong with my code? How to get my new value

I have a form and calculation formula. I need to get my result in inpute string.
my table
<table class="vel_sum_table" style="font-size: 9pt;">
<tr>
<td><?php echo __( 'In package м<sup>2</sup>:', 'wqc' ); ?></td>
<td> <span><?php echo number_format((get_post_meta($post->ID,"_calculatorscript_value",true)),2,",",""); ?> </span>
</td>
</tr>
<tr>
<td><?php echo __( 'Total:', 'wqc' ); ?></td>
<td><input type="text" value="" name="quantity2" id="quantity_product_input" disabled style="border: none;color: #000;font-weight: bold;"/>
</td>
</tr>
</table>
I need to get my result in quantity_product_input inpute. My script, I think, works. input[name=quantity] are on the page. It is product page woocommerce.
<script>
jQuery(document).ready(function($){
var pakket_variable = <?php echo $calculatorValue; ?>;
$('input[name=quantity]').on( 'input change', function(){
var productQty = $(this).val() == '' ? 1 : $(this).val();
meterM2 = (pakket_variable * productQty);
$('#quantity_product_input').val(meterM2);
}
}}
</script>

JS function addEventListener just works on the first element of my list

I display a user list and at the end of each user I add 2 buttons, one for edit and the other to delete the user, my big problem is that only the buttons of my first element of my list work.
This code displays my list
<tbody>
<?php for( $i = 0; $i < count($users->datos); $i++ ): ?>
<tr>
<td style="padding: 0 20px;"><?php echo $users->datos[$i]["email" ]; ?></td>
<td style="padding: 0 20px;"><?php echo $users->datos[$i]["paterno"]; ?></td>
<td style="padding: 0 20px;"><?php echo $users->datos[$i]["materno"]; ?></td>
<td style="padding: 0 20px;"><?php echo $users->datos[$i]["nombre" ]; ?></td>
<td style="padding: 0 20px;">
<?php
echo preg_replace(PHONE_NUMBER, "($1) $2-$3", $users->datos[$i]["movil"]);
?>
</td>
<td id="botones">
<form id="ed" method="POST">
<input type="hidden" id="token" name="token" value="<?php echo $users->datos[$i]["tokenA"]; ?>">
<button type="submit" id="<?php echo $users->datos[$i]["id"]; ?>" class="buttonDelete"><i class="fas fa-trash-alt"></i></button>
<button type="submit" id="<?php echo $users->datos[$i]["id"]; ?>" class="buttonEdit" ><i class="fas fa-edit" ></i></button>
</form>
</td>
</tr>
<?php endfor; ?>
</tbody>
And this is my javascript code
const formEditDel = document.querySelector('form#ed');
const userDel = formEditDel.querySelectorAll('[class="buttonDelete"]')
const userEdit = formEditDel.querySelectorAll('[class="buttonEdit"]')
eventListeners();
function eventListeners(event) {
userDel.forEach(button => {
button.addEventListener('click', markDeleted);
});
userEdit.forEach(button => {
button.addEventListener('click', userEdited);
});
}
I really don't know what to do, so any suggestion will be appreciated.
Since every row contains a separate form, so using an id to select them will only select the first one.
So, you can replace this
const userDel = formEditDel.querySelectorAll('[class="buttonDelete"]')
const userEdit = formEditDel.querySelectorAll('[class="buttonEdit"]')
With this
const userDel = document.querySelectorAll('[class="buttonDelete"]')
const userEdit = document.querySelectorAll('[class="buttonEdit"]')
Or you can replace this
<form id="ed" method="POST"> ... </form>
With this
<form class="ed" method="POST"> ... </form>
And then select the form using class
const formEditDel = document.querySelector('form.ed');
Thanks to #Taplar and #imvain2 I could get an answer to this question and understand how this works. THANK YOU GUYS!
Here is the final code
const userDel = document.querySelectorAll('.buttonDelete');
const userEdit = document.querySelectorAll('.buttonEdit');
eventListeners();
function eventListeners(event) {
userDel.forEach(buttonDel => {
buttonDel.addEventListener('click', markDeleted);
});
userEdit.forEach(buttonEdit => {
buttonEdit.addEventListener('click', userEdited);
});
}

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

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

AJAX JSON loaded form buttons refreshes page instead on working with AJAX again

I have a strange problem here. I am processing data via AJAX from a table loaded inside while loop and when the data is successfully processed the table gets reloaded with new data via AJAX and JSON. The problem is that when the new table is loaded and I click the same submit button from any row again then this time instead of processing it via AJAX it works as a normal submit button and refreshes the page. Then when the page is refreshed the submit button works via AJAX again. Why is it not working with AJAX when the table was reloaded via AJAX after previous operation via AJAX when in both the tables the parameters used are exactly the same? My codes are below. Please tell my what's wrong here and what's the solution for this.
membership.php
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Memberships List</h3>
</div>
<div class="card-body table-responsive p-0">
<table class="table table-hover table-striped" id="mbslist">
<tr>
<th>ID</th>
<th>Name</th>
<th>Daily Capping</th>
<th>Commission</th>
<th>Payout</th>
<th>Payout %</th>
<th>Cost</th>
<th>Status</th>
<th>Action</th>
</tr>
<?php
$i = 1;
$mem = $pdo->prepare("SELECT * FROM memberships");
$mem-> execute();
while($m = $mem->fetch()){ extract($m);
if($mem_status == 'enabled'){
$statusColor = "text-success";
$btn = "btn-danger";
$status = "disabled";
$btnVal = "Disable";
}else{
$statusColor = "text-danger";
$btn = "btn-success";
$status = "enabled";
$btnVal = "Enable";
}
?>
<tr>
<td><?php echo $i; ?></td>
<td><span style="color: <?php echo $mem_color; ?>"><?php echo $mem_name; ?></span></td>
<td>₹<?php echo $mem_daily_capping; ?></td>
<td>₹<?php echo $mem_earn_amount; ?></td>
<td>₹<?php echo $mem_min_payout; ?></td>
<td><?php echo $mem_payout_percent; ?>%</td>
<td><?php if($mem_price == '0.00'){ echo "Free"; }else{ echo "₹$mem_price"; } ?></td>
<td><span class="<?php echo $statusColor; ?>"><?php echo ucfirst($mem_status); ?></span></td>
<td>
<form method="post" action="">
<input type="hidden" value="<?php echo $mem_id; ?>" class="memid">
<input type="hidden" value="<?php echo $status; ?>" class="status">
<input type="hidden" value="memstatus" class="type">
<?php if($mem_id != 1){ ?>
<input type="submit" class="btn <?php echo $btn; ?> mbslist" value="<?php echo ucfirst($btnVal); ?>">
<?php } ?>
Edit
</form>
</td>
</tr>
<?php $i++; } ?>
</table>
</div>
</div>
</div>
<div class="message"></div>
</div>
AJAX Code
// Set Membership Status
$(document).ready(function(){
$(".mbslist").click(function() {
var dataString = {
id: $(this).closest('tr').find('.memid').val(),
type: $(this).closest('tr').find('.type').val(),
status: $(this).closest('tr').find('.status').val()
};
console.log(dataString);
$.ajax({
type: "POST",
dataType : "json",
url: "processes/memberships.php",
data: dataString,
cache: true,
beforeSend: function(){
$('.message').hide();
$('.overlay').fadeIn();
},
success: function(json){
$('.message').html(json.status);
setTimeout(function(){
$('.overlay').fadeOut();
$('.message').fadeIn();
$('#mbslist').html(json.table).fadeIn();
}, 2000);
}
});
return false;
});
});
processes/memberships.php
<?php
include('../../config/db.php'); include('../../functions.php');
$memid = (!empty($_POST['id']))?$_POST['id']:null;
$type = (!empty($_POST['type']))?$_POST['type']:null;
$status = (!empty($_POST['status']))?$_POST['status']:null;
$color = (!empty($_POST['color']))?$_POST['color']:null;
$name = (!empty($_POST['name']))?$_POST['name']:null;
$capping = (!empty($_POST['capping']))?$_POST['capping']:null;
$amount = (!empty($_POST['amount']))?$_POST['amount']:null;
$minpay = (!empty($_POST['minpay']))?$_POST['minpay']:null;
$percent = (!empty($_POST['percent']))?$_POST['percent']:null;
$price = (!empty($_POST['price']))?$_POST['price']:null;
if($_POST){
if($type == 'memstatus'){
$update = $pdo->prepare("UPDATE memberships SET mem_status = :status WHERE mem_id = :id");
$update-> bindValue(':status', $status);
$update-> bindValue(':id', $memid);
$update-> execute();
if($update){
$pro = $pdo->prepare("SELECT * FROM memberships");
$pro-> execute();
$table = "<table class='table table-hover table-striped' id='mbslist'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Daily Capping</th>
<th>Commission</th>
<th>Payout</th>
<th>Payout %</th>
<th>Cost</th>
<th>Status</th>
<th>Action</th>
</tr>";
$i = 1;
while($p = $pro->fetch()){ extract($p);
if($mem_status == 'enabled'){
$statusColor = "text-success";
$btn = "btn-danger";
$status = "disabled";
$btnVal = "Disable";
}else{
$statusColor = "text-danger";
$btn = "btn-success";
$status = "enabled";
$btnVal = "Enable";
}
if($mem_price == '0.00'){ $mp = "Free"; }else{ $mp = $mem_price; }
$table .= "<tr>
<td>".$i."</td>
<td><span style='color: ".$mem_color."'>".$mem_name."</span></td>
<td>₹".$mem_daily_capping."</td>
<td>₹".$mem_earn_amount."</td>
<td>₹".$mem_min_payout."</td>
<td>".$mem_payout_percent."%</td>
<td>".$mp."</td>
<td><span class=".$statusColor.">".ucfirst($mem_status)."</span></td>
<td>
<form method='post' action=''>
<input type='hidden' value=".$mem_id." class='memid'>
<input type='hidden' value=".$status." class='status'>
<input type='hidden' value='memstatus' class='type'>
<input type='submit' class='btn ".$btn." mbslist' value=".ucfirst($btnVal).">
<a href='?mem=".$mem_id."&action=edit' class='btn btn-primary'>Edit</a>
</form>
</td>
</tr>";
$i++;
}
$table .= "</table>";
echo json_encode(array('status' => alert_success_dismiss("Membership has been ".$status."."), 'table' => $table));
}else{
echo json_encode(array('status' => alert_danger_dismiss("Server Error! Please refresh the page and try again.")));
}
}
}
Modify your processes/memberships.php with following code:
$memid = (!empty($_POST['id']))?$_POST['id']:null;
$type = (!empty($_POST['type']))?$_POST['type']:null;
$status = (!empty($_POST['status']))?$_POST['status']:null;
$color = (!empty($_POST['color']))?$_POST['color']:null;
$name = (!empty($_POST['name']))?$_POST['name']:null;
$capping = (!empty($_POST['capping']))?$_POST['capping']:null;
$amount = (!empty($_POST['amount']))?$_POST['amount']:null;
$minpay = (!empty($_POST['minpay']))?$_POST['minpay']:null;
$percent = (!empty($_POST['percent']))?$_POST['percent']:null;
$price = (!empty($_POST['price']))?$_POST['price']:null;
if($_POST){
if($type == 'memstatus'){
$update = $pdo->prepare("UPDATE memberships SET mem_status = :status WHERE mem_id = :id");
$update-> bindValue(':status', $status);
$update-> bindValue(':id', $memid);
$update-> execute();
if($update){
$pro = $pdo->prepare("SELECT * FROM memberships");
$pro-> execute();
$table = "<table class='table table-hover table-striped' id='mbslist'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Daily Capping</th>
<th>Commission</th>
<th>Payout</th>
<th>Payout %</th>
<th>Cost</th>
<th>Status</th>
<th>Action</th>
</tr>";
$i = 1;
while($p = $pro->fetch()){ extract($p);
if($mem_status == 'enabled'){
$statusColor = "text-success";
$btn = "btn-danger";
$status = "disabled";
$btnVal = "Disable";
}else{
$statusColor = "text-danger";
$btn = "btn-success";
$status = "enabled";
$btnVal = "Enable";
}
if($mem_price == '0.00'){ $mp = "Free"; }else{ $mp = $mem_price; }
$table .= "<tr>
<td>".$i."</td>
<td><span style='color: ".$mem_color."'>".$mem_name."</span></td>
<td>₹".$mem_daily_capping."</td>
<td>₹".$mem_earn_amount."</td>
<td>₹".$mem_min_payout."</td>
<td>".$mem_payout_percent."%</td>
<td>".$mp."</td>
<td><span class=".$statusColor.">".ucfirst($mem_status)."</span></td>
<td>
<form method='post' action=''>
<input type='hidden' value=".$mem_id." class='memid'>
<input type='hidden' value=".$status." class='status'>
<input type='hidden' value='memstatus' class='type'>
<input type='submit' class='btn ".$btn." mbslist' value=".ucfirst($btnVal).">
<a href='?mem=".$mem_id."&action=edit' class='btn btn-primary'>Edit</a>
</form>
</td>
</tr>";
$i++;
}
$table .= "</table>";
echo json_encode(array('status' => alert_success_dismiss("Membership has been ".$status."."), 'table' => $table));
}else{
echo json_encode(array('status' => alert_danger_dismiss("Server Error! Please refresh the page and try again.")));
}
}
}
?>
<script>
// Set Membership Status
$(document).ready(function(){
$(".mbslist").click(function() {
var dataString = {
id: $(this).closest('tr').find('.memid').val(),
type: $(this).closest('tr').find('.type').val(),
status: $(this).closest('tr').find('.status').val()
};
console.log(dataString);
$.ajax({
type: "POST",
dataType : "json",
url: "processes/memberships.php",
data: dataString,
cache: true,
beforeSend: function(){
$('.message').hide();
$('.overlay').fadeIn();
},
success: function(json){
$('.message').html(json.status);
setTimeout(function(){
$('.overlay').fadeOut();
$('.message').fadeIn();
$('#mbslist').html(json.table).fadeIn();
}, 2000);
}
});
return false;
});
});
</script>
Hope this might help you.
Your submit button will try to submit form normally when you click it. So just use "event.preventDefault() " as below so your button wont trigger normal form submission and now wont load the page.
$(".mbslist").click(function(event) {
event.preventDefault();
}

how to use popup and action together in href tag

I want to open a cart modal (popup which includes the item you just clicked i am trying like this
<a class="btnLink" data-rel="popup" data-transition="slidedown" href="?action=addToCart&PROD_ID=<?php echo $row["PROD_ID"]; ?>#cart">Add to cart</a></in>
this is the part i want to open in popup but only to able to perform popup but not able to perform action
<div id="cart">
<?php
// initializ shopping cart class
include 'Cart.php';
$cart = new Cart;
include 'db_const.php';
if(isset($_REQUEST['action']) && !empty($_REQUEST['action'])){
if($_REQUEST['action'] == 'addToCart' && !empty($_REQUEST['PROD_ID'])){
$productID = $_REQUEST['PROD_ID'];
// get product details
$stmt = "SELECT * FROM RETAIL_STORE_PROD WHERE PROD_ID = '$productID'";
$result = db2_prepare($conn, $stmt);
db2_execute($result);
$row = db2_fetch_assoc($result);
$itemData = array(
'PROD_ID' => $row['PROD_ID'],
'PROD_NM' => $row['PROD_NM'],
'MRP' => $row['MRP'],
'qty' => 1
);
$insertItem = $cart->insert($itemData);
//$redirectLoc = $insertItem?'viewCart.php';
//header("Location: ".$redirectLoc);
}elseif($_REQUEST['action'] == 'updateCartItem' && !empty($_REQUEST['PROD_ID'])){
$itemData = array(
'rowid' => $_REQUEST['PROD_ID'],
'qty' => $_REQUEST['qty']
);
$updateItem = $cart->update($itemData);
echo $updateItem?'ok':'err';die;
}elseif($_REQUEST['action'] == 'removeCartItem' && !empty($_REQUEST['PROD_ID'])){
$deleteItem = $cart->remove($_REQUEST['PROD_ID']);
header("Location: viewCart.php");
}elseif($_REQUEST['action'] == 'placeOrder' && $cart->total_items() > 0 && !empty($_SESSION['sessCustomerID'])){
// insert order details into database
// insert order items into database
// $insertOrderItems = $db->multi_query($sql);
}
}
?>
<title>Shopping Cart</title>
<meta charset="utf-8">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css<script>
function updateCartItem(obj,PROD_ID){
$.get("cartAction.php", {action:"updateCartItem", PROD_ID:PROD_ID, qty:obj.value}, function(data){
if(data == 'ok'){
location.reload();
}else{
alert('Cart update failed, please try again.');
}
});
}
</script>
<h1>Shopping Cart</h1>
<table border="0" class="table_fields" id="t01" cellpadding="2px" cellspacing="20px" style="width:100%">
<tr class="table_fields_top">
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
<th>Subtotal</th>
<th> </th>
</tr>
<tbody>
<?php
if($cart->total_items() > 0){
//get cart items from session
$cartItems = $cart->contents();
foreach($cartItems as $item){
?>
<tr class="table_fields_top">
<td><?php echo $item["PROD_NM"]; ?></td>
<td><?php echo 'Rs'.$item["MRP"].' '; ?></td>
<td><input type="number" class="form-control text-center" value="<?php echo $item["qty"]; ?>" onchange="updateCartItem(this, '<?php echo $item["rowid"]; ?>')"></td>
<td><?php echo 'Rs'.$item["subtotal"].''; ?></td>
<td>
<!--<i class="glyphicon glyphicon-refresh"></i>-->
<img border="0" alt="Delete_button.png" src="Delete_button.png" width="50" height="50">
</td>
</tr>
<?php } }else{ ?>
<tr><td colspan="5"><p>Your cart is empty.....</p></td>
<?php } ?>
</tbody>
<tfoot>
<tr>
<td><a class="btn btn-primary" href="billing.php"><i class="glyphicon glyphicon-menu-left"></i> <img src="images/button_continue-shopping.png"></a></td>
<td colspan="2"></td>
<?php if($cart->total_items() > 0){ ?>
<td class="text-center"><strong>Total: <?php echo 'RS'.$cart->total().''; ?></strong></td>
<td><img src="images/button_checkout.png <i class="glyphicon glyphicon-menu-right"></i><img src="images/button_checkout.png"></td>
<?php } ?>
</tr>
</tfoot>
</table>
Instead call one single function on href click and in that function first open popup and then perform your task which you are going to perform.
<a class="btnLink" href="#" onclick="demo_funtion(<?php echo $row["PROD_ID"]; ?>)">Add to cart</a>
function demo_function(cart_id){
$("#modal_id").show();
/*
write task you have to perform in action
*/
}

Categories

Resources