Updating array value on input change - javascript

I am trying to update my quantity values saved in array so when i update quantity it is also saved after refresh. Problem is that when i am always updating same item, even when i have multiple items in cart and i try to change quantity of each, it changes quantity of only one item. I am bit lost in these loops, i tried to move the update section out of while but it didnt help. Also when I don't have unset($_POST['qt']) it changes all items quantity in cart, which is wrong.
foreach ($_SESSION['cart'] as $index => $item) {
foreach ($item as $id => $quantity) {
$sql = "SELECT name, image, quantity, price FROM product WHERE product.id_p = ?";
$stmt = $db->prepare($sql);
$stmt->bind_param('s', $id);
$stmt->execute();
$stmt->bind_result($name, $image, $maxquantity, $price);
while($stmt->fetch()) : ?>
<tr>
<td><?=$image?></td>
<td><?=$name?></td>
<td><?=$id?></td>
<td><input type="number" class="form-control quantitycart" data-id="<?=$id?>" min="1" max="<?=$maxquantity?>" data-min="1" data-max="<?=$maxquantity?>" name="quantitycart" value="<?=$quantity = ($quantity > $maxquantity) ? $maxquantity : $quantity; ?>"/></td>
<td>€<span class="price"><?=$price * $quantity?></span>
<input type="hidden" class="real_price" value="<?=$price?>"/></td>
<td><?=$id?><span class="glyphicon glyphicon-remove-sign"/></td>
<tr>
<?php
if(isset($_POST['qt']) && isset($_POST['idupd'])){
$_SESSION['cart'][$index][$_POST['idupd']] = $_POST['qt'];
unset($_POST['qt']);
unset($_POST['idupd']);
}
endwhile;
$stmt->close(); }
}
}
JS
$('.quantitycart').change(function(){
var container = $(this).parents('tr');
var price = container.find('.real_price').val() * 1;
var qty = $(this).val() * 1;
var total = price * qty;
var id = $(this).data('id');
container.find('.price').html(total);
$.ajax({
type: 'POST',
cache: false,
data: {qt: qty, idupd: id},
url: 'includes/cartbody.php',
success: function(data){
}
});
});
EDIT:
if(isset($_POST['qt']) && isset($_POST['idupd'])){
$_SESSION['cart'][$index][$_POST['idupd']] = $_POST['qt'];
unset($_POST['qt']);
unset($_POST['idupd']);
}

Related

AJAX filling table input array fields

I have a form which contains a table with input fields. I want to the select input fields of the second to be updated based on the selected value of first
using AJAX
<td><select class='form-control select2' id='name[]' name='name[]' onchange="getSize(this);">
<option> select </option>
<?php
$sql = "SELECT DISTINCT table_name FROM m_table ORDER BY 1 ASC";
$res = pg_query($conn,$sql);
$num_row = pg_num_rows($res);
if($num_row > 0)
{
while ($row=pg_fetch_row($res))
{
echo '<OPTION VALUE="'.trim($row['0']).'" >'.trim($row['0']).'</OPTION>';
}
}
?>
</select>
</td>
<td><select class='form-control select2' id='m_size[]' name='m_size[]' >
<!------------------------------------>
<!------------------------------------>
</select>
</td>
How shall I get the value of name[] inside jquery?
How shall I update the value of m_size[]?
I was troubling with the issue. Hope this answer will help someone.
function getSize(e){
var tr = $(e).closest("tr");
var rowindex = tr.index() ;
var NAME = document.forms[0].elements["name[]"];
var name = NAME[rowindex].value;
var gsizeOptions = null;
$.ajax({
url:"getSize.php",
type:"POST",
data:{name:name},
dataType: 'html',
//async: false,
success: function(data){
console.log(data);
sizeOptions = data;
var MSIZE= document.forms[0].elements["m_size[]"];
$(MSIZE[rowindex]).append(sizeOptions);
}
});
}

How can I get my information to display into a link <a href> or a <div>?

The issue I am having is that I need the search results to be displayed in a link or a . Right now they display into a text input field. When I try to change it to a link or div no text is generated. I am almost certain it has to do with the java/jquery script I have. The script I am using is an open source script that I need for simple reasons.
What I have tried is changing the element in which the script calls for from an input to a div or a href. I have googled and tried to find some sort of reference to which the script selects what elements to display the code into and the only thing I can identify as being the problem is, "userid = ui.item.value; // selected id to input".
index.php - Script
<script type="text/javascript">
$(document).ready(function(){
$(document).on('keydown', '.username', function() {
var id = this.id;
var splitid = id.split('_');
var index = splitid[1];
$( '#'+id ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "getDetails.php",
type: 'post',
dataType: "json",
data: {
search: request.term,request:1
},
success: function( data ) {
response( data );
}
});
},
select: function (event, ui) {
$(this).val(ui.item.label); // display the selected text
var userid = ui.item.value; // selected id to input
// AJAX
$.ajax({
url: 'getDetails.php',
type: 'post',
data: {userid:userid,request:2},
dataType: 'json',
success:function(response){
var len = response.length;
if(len > 0){
var name = response[0]['name'];
var displayid = response[0]['displayid'];
document.getElementById('name_'+index).value = name;
document.getElementById('displayid_'+index).value = displayid;
}
}
});
return false;
}
});
});
// Add more
$('#addmore').click(function(){
// Get last id
var lastname_id = $('.tr_input input[type=text]:nth-child(1)').last().attr('id');
var split_id = lastname_id.split('_');
// New index
var index = Number(split_id[1]) + 1;
// Create row with input elements
var html = "<tr class='tr_input'><td><input type='text' class='username' id='username_"+index+"' placeholder='Enter username'></td><td><input type='text' class='name' id='name_"+index+"' ></td><td><input type='text' class='displayid' id='displayid_"+index+"' ></td></tr>";
// Append data
$('tbody').append(html);
});
});
</script>
index.php - Html
<div class="container">
<table border='1' style='border-collapse: collapse;'>
<thead>
<tr>
<th>Search</th>
<th>Name</th>
<th>Display ID</th>
</tr>
</thead>
<tbody>
<tr class='tr_input'>
<td><input type='text' class='username' id='username_1' placeholder='Enter username'></td>
<td><input type='text' class='name' id='name_1' readonly></td>
<td><input type='text' class='displayid' id='displayid_1' readonly></td>
</tr>
</tbody>
</table>
<br>
<input type='button' value='Add more' id='addmore'>
</div>
getDetails.php
$request = $_POST['request']; // request
// Get username list
if($request == 1){
$search = $_POST['search'];
$query = "SELECT * FROM item_template WHERE name like'%".$search."%'";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result) ){
$response[] = array("value"=>$row['entry'],"label"=>$row['name']);
}
// encoding array to json format
echo json_encode($response);
exit;
}
// Get details
if($request == 2){
$userid = $_POST['userid'];
$sql = "SELECT * FROM item_template WHERE entry=".$userid;
$result = mysqli_query($con,$sql);
$users_arr = array();
while( $row = mysqli_fetch_array($result) ){
$userid = $row['entry'];
$name = $row['name'];
$displayid = $row['displayid'];
$users_arr[] = array("entry" => $userid, "name" => $name,"displayid" => $displayid);
}
// encoding array to json format
echo json_encode($users_arr);
exit;
}
I except the selector is wrong in the script, where it selects where to copy the text to.
You just need to use innerHTML instead of value.
document.getElementById('name_'+index).innerHTML = name;
document.getElementById('displayid_'+index).innerHTML = displayid;
and change the input tag to div tag. You might want to read more about innerHTML.

Php updating a span using javascript/ajax is not working properly

I am updating a span using below script but it is working if condition is false and if condition is true it does not update.
What i observed that it executes the same false condition and when i click the second time it updates the quantity but less 1 number than the actual quantity of records in the database.
Like total records are 2 and when i click submit the script runs and if condition is true in the database records are updated = 3 but in the span it shows 2.
When i click 2nd time and in the database records are = 4 and in the span it shows 3.
Button where i click and run the script
<input onclick='updateTitems("1");' type="submit" class="btn-style-2 mg-left-5" value="ADD TO CART">
script
<script>
function updateTitems(id) {
var uid = "<?php echo $ses_mem; ?>";
$.ajax({
type: "GET",
url: 'inc/menu_update_total_items.php',
data: "id=" + id + "&uid=" + uid,
success: function(data) {
$('.summary12').html(data);
}
});
}
</script>
menu_update_total_items.php
$user_id = $_GET['uid'];
$item = "select count(*) as records
from orders_temp
where user_id = '".$user_id."'
";
$itemq = $dba->query($item);
$itemr = $itemq->fetch_assoc();
$count = $itemr['records'];
---------------------------------
$itemx = "select count(*) as records
from orders_temp
where date = now()
and user_id = '".$user_id."'
";
$itemqx = $dba->query($itemx);
$itemrx = $itemqx->fetch_assoc();
$check = $itemrx['records'];
<span class="summary12"><!-- class of javascript -->
<?php
if ($check == 1){
echo $count+1;
}else{
echo $count;
}
?>
Items
</span>
After trying lot of things i came up with the following solution and the issue has been solved.
Please need your opinion on this. Thanks
Button
<input onclick='updateTitems();' type="submit" class="btn-style-2 mg-left-5" value="ADD TO CART">
Script
function updateTitems(){
$.ajax({
url: "menu_update_total_items.php",
cache: false,
success: function(data){
$(".summary12").html(data);
//div or span reload script after success
setInterval(function () {
$('.summary12').load('inc/menu_update_total_items.php');
}, 1000);
}
});
}
menu_update_total_items.php
<?php
#session_start();
include ("inc/db.php");
$ses_mem = session_id();
$items = "select count(*) as trecords
from orders_temp
where user_id = '".$ses_mem."' ";
$item = $dba->query($items);
$count = $toitemszx->fetch_assoc();
?>
<a href="cart/review" class="cart-link">
<i class="fa fa-shopping-basket"></i>
<?php echo $count['trecords']; ?>
Items
</a>

Save data on database after click on place order

What's wrong with my code? I can't even place an order or save it on database. I'm using ajax/jquery, it reaches the success but the problem is, it doesn't save in database.
PS: I also included place_order(); under script type.
Button:
<button id="place_order" class="btn btn-black">PLACE ORDER</button>
Jquery:
//Placing Order / Complete the Transaction
function place_order() {
$('#place_order').click(function(e){
var place_order = $('#place_order').val();
$.ajax({
type: 'POST',
url: '../pages/class.php',
data: {place_order:place_order},
success:function(data) {
location.href="../pages/index.php";
}
});
});
}
Class.php
if(isset($_POST['place_order'])) {
if(isset($_SESSION['item_cart'])) {
foreach($_SESSION['item_cart'] as $id=>$val) {
$user_id = $_SESSION['id']; //id of users
$product_stocks = $val['product_stocks']; //product stocks
$product_id = $val['product_id']; //id of product/item
$product_name = $val['product_name']; //name of product
$product_quantity = $val['product_qty']; //quantity of product
$product_price = $val['product_price']; //price of product
$product_size = $val['product_size']; //size of product
//Total Price
$total = $product_quantity * $product_price;
//Check if the stocks is less than quantity
if ($product_stocks < $product_quantity) {
echo "Insufficient Stock";
} else {
//Insert it on database
$insert_query = "INSERT INTO tbltransactions(product_name, product_price, product_qty, total_price, product_id, account_id) VALUES('$product_name', $product_price, $product_quantity, $total, $product_id, $user_id)";
$query = mysqli_query($db_conn, $insert_query);
//If the query is success, update the stocks in database
if($query) {
$update_query = "UPDATE tblproduct_extension SET product_stocks = $product_stocks - $product_quantity WHERE product_id = '$product_id' AND product_size='$product_size'";
$query = mysqli_query($db_conn, $update_query);
//unset the SESSION
unset($_SESSION['item_cart']);
}
}
}
}
}
There is no value assigned to the variable place_order
data: {place_order:place_order},
Assign value to variable using
var place_order = $("#place_order").val(); //change field name

i am making Point of Sale and i want to get nettotal of the products, using ajax but i am having trouble in it

this is my javascript
<script>
function multiply(id) {
var quantity = $("#quantity"+id).val();
var price = $("#price"+id).text();
var dataArray= 'quantity1='+ quantity + '&price1='+ price;
$.ajax({
url: "ajaxmultiply.php",
data: dataArray,
type: 'POST',
success: function (data) {
$("#total"+id).(data);
}
});
}
</script>
I am able to get the total of the products but i am having issue in getting net total of the product, i am doing this using ajax, when i add the total it will give me previous value as concatenated with next value,i tried using through array but it also didn't work, now i store the total value in new table and then fetch it from there and add it but i didn't give me required answer, i tried to use array in it but it also didn't work for me
This is my ajaxmultiply.php file code
<?php
include 'connection.php';
$quantity=$_POST['quantity1'];
$price = $_POST['price1'];
$total= $quantity * $price;
//echo $total;
$query =mysqli_query ($conn,"INSERT INTO grand_total (total) VALUES
('$total')");
$getdata=mysqli_query($conn,"SELECT * FROM grand_total");
while ($fetchdata=mysqli_fetch_assoc($getdata)){
$newtotal = $fetchdata['total'];
$id = $fetchdata['id'];
$grandTotal=$newtotal + $newtotal;
echo $grandTotal;
}
Your while loop should be like below:
$grandTotal = 0;
while ($fetchdata=mysqli_fetch_assoc($getdata)){
$newtotal = $fetchdata['total'];
$id = $fetchdata['id'];
$grandTotal += $newtotal;
}
echo $grandTotal;

Categories

Resources