How to get values from foreach loop of php in jquery - php

I'm Working on a plugin in Wordpress in which i'm storing values in new table which is created on plugin activation its working perfectly.
Now I fetched values from table like following
<tbody>
<?php
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM wp_ajc_images");
foreach ($result as $row) {
?>
<tr id="list_item">
<td width="12%">
<img src="<?php echo $row->ajc_img_path ?>" width="100">
</td>
<td width="22%">
<input type="text" class="img_link" value="<?php $row->ajc_img_link ?>" size="30">
<input type="hidden" class="ajc_field_id" value="<?php echo $row->ajc_img_id ?>">
</td>
<td width="26%">
<textarea rows="3" class="img_description"><?php $row->ajc_img_description ?></textarea>
</td>
<td width="22%">
<input type="text" class="img_title" value="<?php $row->ajc_img_title ?>" size="30">
</td>
<td width="20%">
<input type="submit" id="update" value="Update">
<button class="delete">Delete</button>
</td>
</tr>
<?php
}
?>
</tbody>
after fetching the data I display the values in form of listing.
Now I want to update values of input fields and textarea through ajax for which I wrote following code
add_action('wp_ajax_ajc_update_values', 'ajc_update_value');
add_action('wp_ajax_nopriv_ajc_update_values', 'ajc_update_value');
add_action("admin_head", "ajc_input_ajax");
function ajc_input_ajax()
{
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#update").click(function () {
var id = jQuery('.ajc_field_id').val();
var update_link = jQuery('.img_link').val();
var update_desc = jQuery('.img_description').val();
var update_title = jQuery('.img_title').val();
alert(id);
var data = {
action: 'ajc_update_values',
ajc_id: id,
ajc_update_link: update_link,
ajc_update_desc: update_desc,
ajc_update_title: update_title
};
alert(data.toSource());
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function (result) {
// alert(result);
});
});
});
</script>
<?php
}
//Updating values in database
function ajc_update_value()
{
$id = $_POST['ajc_id'];
$link = $_POST['ajc_update_link'];
$desc = $_POST['ajc_update_desc'];
$title = $_POST['ajc_update_title'];
global $wpdb;
$wpdb->update(
'wp_ajc_images',
array(
'ajc_img_title' => $title,
'ajc_img_description' => $desc,
'ajc_img_link' => $link
),
array('ajc_img_id' => $id)
)
die();
return true;
}
When I click on first item's update button it alerts me right id eg. (12) and update it, but when I click on rest of the item's update button it alerts me first item's id (12) and data is not updated.
Hope you'll understand my question.

Try this code. add id to every fields like id="img_link_<?php echo $row->ajc_img_id; ?>"
HTML code
<tbody>
<?php
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM wp_ajc_images");
foreach ($result as $row) {
?>
<tr id="list_item">
<td width="12%">
<img src="<?php echo $row->ajc_img_path ?>" width="100">
</td>
<td width="22%">
<input type="text" id="img_link_<?php echo $row->ajc_img_id; ?>" class="img_link" value="<?php $row->ajc_img_link ?>" size="30">
<input type="hidden" class="ajc_field_id" value="<?php echo $row->ajc_img_id; ?>">
</td>
<td width="26%">
<textarea rows="3" id="img_description_<?php echo $row->ajc_img_id; ?>" class="img_description"><?php $row->ajc_img_description ?></textarea>
</td>
<td width="22%">
<input type="text" id="img_title_<?php echo $row->ajc_img_id; ?>" class="img_title" value="<?php $row->ajc_img_title ?>" size="30">
</td>
<td width="20%">
<input type="submit" data-id="<?php echo $row->ajc_img_id; ?>" id="update" value="Update">
<button class="delete">Delete</button>
</td>
</tr>
<?php
}
?>
</tbody>
Script code
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#update").click(function () {
var id =jQuery(this).attr('data-id');
var update_link = jQuery('#img_link'+id).val();
var update_desc = jQuery('#img_description'+id).val();
var update_title = jQuery('#img_title'+id).val();
alert(id);
var data = {
action: 'ajc_update_values',
ajc_id: id,
ajc_update_link: update_link,
ajc_update_desc: update_desc,
ajc_update_title: update_title
};
alert(data.toSource());
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function (result) {
// alert(result);
});
});
});
</script>

You're displaying values based on a class name and there could be many elements with same class name. What you need to do is target specific <tr> and get values from that <tr> only.
So your jQuery code should look like this:
jQuery("#update").click(function () {
var id = $(this).parents('tr').find('.ajc_field_id').val();
var update_link = $(this).parents('tr').find('.img_link').val();
var update_desc = $(this).parents('tr').find('.img_description').val();
var update_title = $(this).parents('tr').find('.img_title').val();
alert(id);
var data = {
action: 'ajc_update_values',
ajc_id: id,
ajc_update_link: update_link,
ajc_update_desc: update_desc,
ajc_update_title: update_title
};
alert(data.toSource());
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function (result) {
// alert(result);
});
});
You just have to add $(this).parents('tr').find before selecting values from every element.

Related

Instant Checkbox update on sql rows with ajax and jquery

Example of what I want:
Hi i want on each row to update instant the checkbox with value 1 when checked and 0 when not checked.
I've make some steps and already taken in a URL via post the values, but I see that updates only on the first row of my table. I think it must have some foreach or loop on ajax to take value to other rows?
This value will export as a URL querystring (ischeck) to an extrnal URL to take import on my function to make the sql query to update the value.
Here is the javascript that for sure want changes about loop that I haven't put on charges.php.
<script>
$(function($) {
var arr = [];
$('input.checkbox').on('change', function() {
var id = "<?php echo $charge['id'] ?>";
var check_active = $(this).is(':checked') ? 1 : 0;
var check_id = $('[id^="checked-]');
arr.push(check_active);
var url = "ajax_ischeck.php?id=" + id + "&ischeked=" + check_active;
console.log("url", url);
if (this.checked) {
$.ajax({
url: url,
type: "GET",
dataType: 'html',
success: function(response) {
},
});
}
});
});
</script>
Here is the table with the input checkbox sry its little big the checkbox is down to last lines on Charges.php:
<tbody>
<?php foreach ($showcharge as $charge) { ?>
<tr>
<td><?php echo htmlspecialchars($charge['created_at']); ?></td>
<td><?php echo htmlspecialchars($charge['tasks']); ?> </td>
<th width="5%"><?php if (empty($charge['taskcharges'])) {
echo "Free";
} else {
echo htmlspecialchars($charge['taskcharges'] . "\xE2\x82\xAc");
} ?></th>
<th width="5%"><?php
if (empty($charge['payment'])) {
echo htmlspecialchars($charge['payment']);
} else {
echo htmlspecialchars($charge['payment'] . "\xE2\x82\xAc");
}
?>
</th>
<th width="5%" id="balance"><?= htmlspecialchars($charge['balance'] . "\xE2\x82\xAc") ?></th>
<th width="10%"><?php if (($charge['payment_date'] == 0000 - 00 - 00)) {
echo "";
} else {
echo htmlspecialchars($charge['payment_date']);
} ?></th>
<th width="10%"><?php echo htmlspecialchars($charge['admin']); ?></th>
<th width="15%"><?php echo htmlspecialchars($charge['comments']); ?></th>
<td class="mytd">
<form action="" method="POST">
<a href="editcharge.php?id=<?php echo $charge['id'];
echo '&custid=' . $customer['id'] ?>" class="btn btn-info " role=" button " aria-disabled=" true">Edit</a>
</form>
<form id="delete-<?php echo $charge['id'] ?>" onSubmit="return confirm('Are you sure you want to delete?')" method="post">
<input type="hidden" name="id_to_delete" value="<?php echo $charge['id'] ?>" />
<input type="submit" class="btn btn-danger" name=" delete" value="delete" />
</form>
<script>
$("#delete").submit(function() {
return confirm("Are you sure you want to delete?");
});
</script>
</td>
<th width="7%"> <input class="checkbox" type="checkbox" checked value="1" id="checked-1" name="checbox"> <label> Success </label> </input> </th>
</tr>
<?php } ?>
</tbody>
The ajax_ischeck.php that gets data from charges.php post :
<?php include('dataprocess.php'); ?>
<?php include('config/pdo_connect.php'); ?>
<?php
$id = $_GET['id'];
$ischeck = $_GET['ischeck'];
if(isset($_GET["ischeck"])){
Data::ischecked($id, $ischeck);
}
and the sql query:
public static function ischecked ($id, $ischeck)
{
$sql = "UPDATE charges SET
ischecked='$ischeck'
WHERE id=$id";
$statement = conn()->prepare($sql);
$statement->execute();
/* echo $sql;
die(); */
if (!$statement) {
echo "\nPDO::errorInfo():\n";
}
}

How to get data from server when I enter something in search box and I press add more button? Adds other row of product search box in jQuery AJAX

Hello every one I need help for getting auto search product values for dynamic adding of a product search box, when I type a product id it will show from product table. Please help me to get a dynamic auto search box.
Here is the code for the main html page:
<table id="row2">
<tr id="row1">
<td>product id</td><td><input type="text" id="pid" class="pid" name="p_id">
<div id="suggesstion-box"></div></td>
<td>product name</td> <td><input type="text" id="pname" name="p_name"></td>
<td>product type</td> <td> <input type="text" id="ptype" name="p_type">
</td>
<td>product colour</td> <td> <input type="text" id="pcolor" name="p_colour"></td>
</tr>
</table>
<button name="b1" id="b1" onClick="addrow()">Add More</button>
This the code for jQuery:
$(document).ready(function(){
$("#pid").keyup(function(){
$.ajax({
type: "POST",
url: "readCountry.php",
data:'keyword='+$(this).val(),
beforeSend: function(){
$("#pid").css("background","#FFF url(LoaderIcon.gif) no-repeat 165px");
},
success: function(data1,data2){
$("#suggesstion-box").show();
$("#suggesstion-box").html(data1);
$("#fname").html(data2);
$("#pid").css("background","#FFF");
}
});
});
});
function addrow()
{
//alert('hello');
$('#row2').append("<tr><td>product id</td><td><input type='text' class='pid' id='pid' name='p_id'><div id='suggesstion-box'></div></td><td>product name</td> <td><input type='text' id='pname' name='p_name'></td><td>product type</td> <td> <input type='text' id='ptype' name='p_type'></td><td>product colour</td><td> <input type='text' id='pcolor' name='p_colour'></td></tr>");
}
function selectCountry(val) {
$("#pid").val(val);
$("#suggesstion-box").hide();
}
function name(val){
$("#pname").val(val);
}
function pt(val){
$("#ptype").val(val);
}
function colour(val){
$("#pcolor").val(val);
}
readcountery.php page code is:
<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["keyword"])) {
$query ="SELECT * FROM raw_product WHERE p_id like '%" . $_POST["keyword"] . "%' ORDER BY p_id LIMIT 0,6";
$result = $db_handle->runQuery($query);
if(!empty($result)) {
?>
<ul id="country-list">
<?php
foreach($result as $country) {
?>
<li onClick="selectCountry('<?php echo $country["p_id"]; ?>'); colour('<?php echo $country["p_color"]; ?>'); pt('<?php echo $country["p_color"]; ?>'); name('<?php echo $country["p_name"]; ?>');"><?php echo $country["p_id"]; echo "-".$country["p_name"]; ?></li>
<?php } ?>
</ul>
<?php } } ?>

Fetch result from Database using Ajax

I want to display info and disable a process button if a certain condition is not met at the point of entering the value(onblur or onkeyup event). I have tried many example but none has given me result. Can someone help me out
The Ajax code:
<script type="text/javascript" src="includes/scripts/newJquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("select.custid").change(function () {
var selectedCustomer = $("#amt").val();
var selectedCustId = $("#custid").val();
$.ajax({
type: "POST",
url: "process-loan.php",
data: {
custQual: selectedCustomer,
custid: selectedCustId
}
}).done(function (data) {
$("#qualify").html(data);
});
});
});
</script>
Below is the php page
<th>Customer No:</th>
<td>
<select name="custid" class="custid" id="custid">
<option>Select Customer No</option>
<?php while ($rw = mysqli_fetch_array($get)) { ?>
<option value="<?php echo $rw['custid'] ?>"><?php echo $rw['custid'] ?></option>
<?php } ?>
</select>
</td>
<tr>
<th>Requesting Amount:</th>
<td><input type="number" name="amount" value="0.00" id="amt"/></td>
</tr>
<tr>
<td id="qualify"> </td>
<td id="qualify"> </td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="save" value="Process Loan" class="btn btn-success" id="pButton"/>
The process-loan.php script that will respond to the ajax call:
<?php
if (isset($_POST["amt"])) {
include 'includes/session.php';
include 'includes/db_connection.php';
$amt = $_GET["amt"];
$custid = $_POST["custid"];
// Query the Databased based on the amount and the UserId
if ($amt !== NULL) {
$gets = "SELECT * FROM tab_customer_dailycontribution WHERE custid='" . $custid . "' AND transactionDate BETWEEN '2015-09-01' AND '2015-09-30'";
$get = mysqli_query($connection, $gets);
$sum = 0.00;
while ($row = mysqli_fetch_array($get)) {
$sum += $row['amountContribute'];
}
if ($sum >= $amt) {
//qualify for loan $ enable the Process Button to save
echo "You are Qualify to Apply";
} else {
//disqualify for loan $ disable the process button until condition is meant.
echo "Insufficient Fund: Unqualify to Apply";
}
//end if condition
}
}
?>
this is for demo so i have commented tour mysql related things:first change your keys in process-loan.php.
your view page:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#pButton").hide();
$("#amt").on("blur",function(){
var selectedCustomer = $("#amt").val();
var selectedCustId = $("#custid").val();
$.ajax({
type: "POST",
url:"process-loan.php",
data:{custQual:selectedCustomer,custid:selectedCustId},
success:function(data){
var data=JSON.parse(data);
$("#qualify").html(data.msg);//your message
if(data.status == 0){
$("#pButton").show();//showing button if qualified
}else{
$("#pButton").hide();
}
}
});
});
});
</script>
<th>Customer No:</th>
<td><select name="custid" class="custid" id="custid">
<option>Select Customer No</option>
<?php $i =0; while($i <4){?>
<option value="<?php echo $i?>"><?php echo $i?></option>
<?php $i++;}?></select></td>
<tr>
<th>Requesting Amount:</th>
<td><input type="number" name="amount" value="0.00" id="amt"/></td>
</tr>
<tr>
<td ><div id="qualify"></div></td><!-- added div in td to show message it can be outside of your table !-->
<td> </td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="save" value="Process Loan" class="btn btn-success" id="pButton"/>
process-loan.php
<?php
if(isset($_POST["custQual"])){
// include 'includes/session.php';
// include 'includes/db_connection.php';
$amt = $_POST["custQual"];//here use $_POST not $_GET
$custid = $_POST["custid"];
// Query the Databased based on the amount and the UserId
if($amt !== NULL){
$sum=100000;//static value for demo
if($sum >= $amt){
//qualify for loan $ enable the Process Button to save
$res["status"]=0;
$res["msg"]="You are Qualify to Apply";
}else{
//disqualify for loan $ disable the process button until condition is meant.
$res["status"]=1;
$res["msg"]= "Insufficient Fund: Unqualify to Apply";
}//end if condition
}else{
$res["status"]=1;
$res["msg"]= "put some amount first";
}
echo json_encode($res);
}

how to update the php variable using jquery variable

Hi I am developing a shopping cart.The products ordered by a customer is shown to him. All the products and their details are stored in a session variable. He can change the quantity of each product, if he wants to.When he changes the quantity of a product,corresponding price changes.This I have done using jquery. Now I need to update the session variable,when he changes the quantity. And I have to display it also.
Here is my code.
<?php
session_start();
include('head.php');
?>
<!DOCTYPE HTML>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$(".myclass").change(function(){
var identifier = $(this).attr('id');
var Qty = $(this).val();
var Price = $("#price_"+identifier).val();//price value
var Total = Qty * Price;
$("#priceDisplay_"+identifier).html(Total);
GrandTotal();
});
GrandTotal();
});
function GrandTotal(){
var GrandTotal=0;
var cart=0;
$(".myclass").each(function(){
var identifier = $(this).attr('id');
var Qty = $(this).val();
var Price = $("#price_"+identifier).val();//price value
cart +=parseInt(Qty);
var Total = Qty * Price;
GrandTotal += Total;
$("#priceDisplay_"+identifier).html(Total);
});
$("#cart").html(cart);
$("#GrandTotal").html(GrandTotal);
}
function RemoveCart(ob){
if (confirm("Are you sure to Remove?"))
{
var IdForRemove =ob.value;
$.ajax({
type: "POST",
url: "RemoveCart.php",
dataType:'json',
data: { id: IdForRemove}
})
.done(function( data ) {
$("#GrandTotal").html(data.Grandtotal);
$("#cart").html(data.cart);
$("#"+IdForRemove).remove();
});
return false;
}
}
</script>
</head>
<body>
<?php
if(empty($_SESSION['items'])){ ?>
<center><b><font color="red">There are no products in your cart!!</font></b></center>
<?php
}
else
{
?>
<b><font color="#0000A0"> Your Shopping Cart!!</font></b><br><br>
<form name="formview" action="orderform.php" method="post">
<?php $count=0;
?>
<table id="mytable" width="50%" cellpadding="1px" cellspacing="3px" border="1" bgcolor="#BDEDFF">
<tr>
<th>Item</th>
<th>Price</th>
<th>Quantity</th>
<th>Subtotal</th>
<th>Remove</th>
</tr>
<?php
$cnt=0;
$CartR = $_SESSION['r'];
foreach( $CartR as $key=>$ar):
$Identifier = 'qty_'.$cnt;
?> <tr id="<?php echo $ar['Id']; ?>">
<td align="center"><?php echo $ar['Name']?></td>
<td align="center"><?php echo $ar['Price']?></td>
<td align="center">
<select class="myclass" name="qty" id='<?php echo $Identifier;?>' >
<?php for ($i=1; $i<=100; $i++) {
$y="";
if( $i==$_SESSION['r'][$key]['Quantity']){
$y="selected";
}
echo "<option ";
echo "value=\"$i\" ".$y.">", $i, "</option>\n";
} ?>
</select>
</td>
<?php $x=$x+$ar['Quantity']; ?>
<td name="price"><span id="priceDisplay_<?php echo $Identifier;?>"><?php echo $ar['Total']; ?></span></td>
<input type='hidden' name='id' id="pid_<?php echo $Identifier;?>" value='<?php echo $ar['Id']; ?>'>
<input type='hidden' name='price' id="price_<?php echo $Identifier;?>" value='<?php echo $ar['Price'] ?>' class="input">
<td>
<input type="checkbox" onclick="RemoveCart(this)" value="<?php echo $ar['Id']; ?>">
<?php $tt[]=$ar['Total']; ?>
</tr>
<?php
$cnt++;
endforeach;
?> </table>
<br><br>
<table>
<tr></tr>
<tr><b><font color="B048B5">Grand Total :</font></b> <span id="GrandTotal"></span></tr>
<b><!--<font color="#F6358A">Your Cart:--></font></b><div align="center" id="cart"></div>
<center> <img src="upload/images.jpeg" width="100"></center>
</table>
<!--<table align="right">-->
<?php foreach($tt as $t)
{
$count=$count+$t;
}
?>
<br>
<br>
<!--<b><div id="cart">Your Cart:</div></b> -->
<?php
}
if(!empty($_SESSION['r']))
{ ?>
<input type="submit" name="checkout" value="CheckOut">
<?php } ?>
<b><font color="#7D0541">Back</font></b>
</form>
</body>
Anyone please help me. The change I made using jquery should also change my php variables.
This is my updated sessionupdate.php
<?php session_start();
include('head.php');
$qnty=$_GET['quantity'];
$prce=$_GET['price1'];
$_SESSION['r']=$_GET['id'];
$pid=$_GET['pid'];
foreach ($_SESSION['r'] as $key => $value) {
if($key==$pid){
$_SESSION['r'][$key]['Quantity']= $qnty;
$_SESSION['r'][$key]['Total']= $prce*$qnty;
}
}
here pid is my product_id passed from ajax.Please help me
If you want to update your php variable then you can do so via ajax.Try to do like this:
$(document).ready(function() {
$(".myclass").change(function(){
var identifier = $(this).attr('id');
var Qty = $(this).val();
var Price = $("#price_"+identifier).val();//price value
var Total = Qty * Price;
$("#priceDisplay_"+identifier).html(Total);
GrandTotal();
//Call an ajax function here
$.ajax({
type: "GET",
url: "sessionupdate.php",
data: { quantity:Qty,price1:Price,id: <?php echo $_SESSION['r'];?>},
success:function(data){
alert(data);
}
});
});
GrandTotal();
});
sessionupdate.php:
<?php session_start();
include('head.php');
$qnty=$_GET['quantity'];
$prce=$_GET['price1'];
$_SESSION['r']=$_GET['id'];
$pid=$_GET['pid'];
foreach ($_SESSION['r'] as $key => $value) {
if($key==$pid){
$_SESSION['r'][$key]['Quantity']= $qnty;
$_SESSION['r'][$key]['Total']= $prce*$qnty;
echo $_SESSION['r'][$key]['Quantity'];
echo $_SESSION['r'][$key]['Total'];
}
}

Updating session variable based on changes made by jquery

Hi I am developing a shopping cart.The products ordered by a customer is shown to him. All the products and their details are stored in a session variable. He can change the quantity of each product, if he wants to.When he changes the quantity of a product,corresponding price changes.This I have done using jquery. Now I need to update the session variable,when he changes the quantity. And I have to display it also.
Here is my code.
<?php
session_start();
include('head.php');
?>
<!DOCTYPE HTML>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$(".myclass").change(function(){
var identifier = $(this).attr('id');
var Qty = $(this).val();
var Price = $("#price_"+identifier).val();//price value
var Total = Qty * Price;
$("#priceDisplay_"+identifier).html(Total);
GrandTotal();
});
GrandTotal();
});
function GrandTotal(){
var GrandTotal=0;
var cart=0;
$(".myclass").each(function(){
var identifier = $(this).attr('id');
var Qty = $(this).val();
var Price = $("#price_"+identifier).val();//price value
cart +=parseInt(Qty);
var Total = Qty * Price;
GrandTotal += Total;
$("#priceDisplay_"+identifier).html(Total);
});
$("#cart").html(cart);
$("#GrandTotal").html(GrandTotal);
}
function RemoveCart(ob){
if (confirm("Are you sure to Remove?"))
{
var IdForRemove =ob.value;
$.ajax({
type: "POST",
url: "RemoveCart.php",
dataType:'json',
data: { id: IdForRemove}
})
.done(function( data ) {
$("#GrandTotal").html(data.Grandtotal);
$("#cart").html(data.cart);
$("#"+IdForRemove).remove();
});
return false;
}
}
</script>
</head>
<body>
<?php
if(empty($_SESSION['items'])){ ?>
<center><b><font color="red">There are no products in your cart!!</font></b> </center>
<?php
}
else
{
?>
<b><font color="#0000A0"> Your Shopping Cart!!</font></b><br><br>
<form name="formview" action="orderform.php" method="post">
<?php $count=0;
?>
<table id="mytable" width="50%" cellpadding="1px" cellspacing="3px" border="1" bgcolor="#BDEDFF">
<tr>
<th>Item</th>
<th>Price</th>
<th>Quantity</th>
<th>Subtotal</th>
<th>Remove</th>
</tr>
<?php
$cnt=0;
$CartR = $_SESSION['r'];
foreach( $CartR as $key=>$ar):
$Identifier = 'qty_'.$cnt;
?> <tr id="<?php echo $ar['Id']; ?>">
<td align="center"><?php echo $ar['Name']?></td>
<td align="center"><?php echo $ar['Price']?></td>
<td align="center">
<select class="myclass" name="qty" id='<?php echo $Identifier;?>' >
<?php for ($i=1; $i<=100; $i++) {
$y="";
if( $i==$_SESSION['r'][$key]['Quantity']){
$y="selected";
}
echo "<option ";
echo "value=\"$i\" ".$y.">", $i, "</option>\n";
} ?>
</select>
</td>
<?php $x=$x+$ar['Quantity']; ?>
<td name="price"><span id="priceDisplay_<?php echo $Identifier;?>"><?php echo $ar['Total']; ?></span></td>
<input type='hidden' name='id' id="pid_<?php echo $Identifier;?>" value='<?php echo $ar['Id']; ?>'>
<input type='hidden' name='price' id="price_<?php echo $Identifier;?>" value='<?php echo $ar['Price'] ?>' class="input">
<td>
<input type="checkbox" onclick="RemoveCart(this)" value="<?php echo $ar['Id']; ?>">
<?php $tt[]=$ar['Total']; ?>
</tr>
<?php
$cnt++;
endforeach;
?> </table>
<br><br>
<table>
<tr></tr>
<tr><b><font color="B048B5">Grand Total :</font></b> <span id="GrandTotal"></span></tr>
<b><!--<font color="#F6358A">Your Cart:--></font></b><div align="center" id="cart"></div>
<center> <img src="upload/images.jpeg" width="100"></center>
</table>
<!--<table align="right">-->
<?php foreach($tt as $t)
{
$count=$count+$t;
}
?>
<br>
<br>
<!--<b><div id="cart">Your Cart:</div></b> -->
<?php
}
if(!empty($_SESSION['r']))
{ ?>
<input type="submit" name="checkout" value="CheckOut">
<?php } ?>
<b><font color="#7D0541">Back</font></b>
</form>
</body>
The change I made using jquery should also change my php variables.
Can you try this.
Added UpdateCart function,
function UpdateCart(Qty, IDCart){
$.ajax({
type: "POST",
url: "UpdateCart.php",
dataType:'json',
data: {id:IDCart, Qty: Qty}
})
.done(function( data ) {
});
return false;
}
$(".myclass").change(function(){
var identifier = $(this).attr('id');
var Qty = $(this).val();
var Price = $("#price_"+identifier).val();//price value
var Total = Qty * Price;
$("#priceDisplay_"+identifier).html(Total);
var IDCart = $("#pid_"+identifier).val();//passing reference value
UpdateCart(Qty, IDCart);//added this for update qty
GrandTotal();
});
GrandTotal();
});
Create one new file : UpdateCart.php
<?php session_start();
if(isset($_POST['id'])){
$toBeUpdate =$_POST['id'];
$CartR =$_SESSION['r'];
$Quantity = $_POST['Qty'];
foreach($CartR as $key=>$Cart){
if($Cart['Id']==$toBeUpdate){
$_SESSION['r'][$key]['Quantity']=$Quantity;
}
}
echo json_encode(array('success'=> true));
}
?>

Categories