Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 用AJAX更新产品的数量有一个问题_Php_Jquery_Ajax - Fatal编程技术网

Php 用AJAX更新产品的数量有一个问题

Php 用AJAX更新产品的数量有一个问题,php,jquery,ajax,Php,Jquery,Ajax,我对使用AJAX来增加产品的数量有一个奇怪的问题 此问题只存在于同一购物车页面上有多个产品的情况下 假设有两种产品。产品订单按产品ID从高到低排序 如果我增加列表中第一个产品的数量,它将成功地增加数量。如果我增加第二个产品的数量,它将成功地增加 但是,如果我选择第二个产品开始并增加它不起作用的数量,那么警报仍然会显示旧的数量(参见Jquery AJAX代码) 当我有3种产品时也会发生同样的情况 仅当我将列表中的数量从上到下更改为从最高ID更改为较低ID时,数量才会更新 我不明白它为什么会这样,我

我对使用AJAX来增加产品的数量有一个奇怪的问题

此问题只存在于同一购物车页面上有多个产品的情况下

假设有两种产品。产品订单按产品ID从高到低排序

如果我增加列表中第一个产品的数量,它将成功地增加数量。如果我增加第二个产品的数量,它将成功地增加

但是,如果我选择第二个产品开始并增加它不起作用的数量,那么警报仍然会显示旧的数量(参见Jquery AJAX代码)

当我有3种产品时也会发生同样的情况

仅当我将列表中的数量从上到下更改为从最高ID更改为较低ID时,数量才会更新

我不明白它为什么会这样,我试了很多,但都没有效果

有人能给我解释一下为什么代码的行为是这样的,以及如何解决这个问题吗

PHP更新_quantity.PHP

<?php
session_start();
include('config/database_connection.php');
// get the product id
echo $id = isset($_GET['id']) ? $_GET['id'] : 1;
echo $quantity = isset($_GET['quantity']) ? $_GET['quantity'] : "";

// make quantity a minimum of 1
$quantity=$quantity<=0 ? 1 : $quantity;

// remove the item from the array
unset($_SESSION['cart'][$id]);

// add the item with updated quantity
$_SESSION['cart'][$id]=array(
    'quantity'=>$quantity
);

?>
使用Jquery-AJAX之前使用的代码,这很有效

    // update quantity button listener
$('.update-quantity-form').on('submit', function(){

    // get basic information for updating the cart
    var id = $(this).find('.product-id').text();
    var quantity = $(this).find('.cart-quantity').val();

    // redirect to update_quantity.php, with parameter values to process the request
    window.location.href = "update_quantity.php?id=" + id + "&quantity=" + quantity;
    return false;
  });
```

将从页面上的第一个表单获取数量,而不是用户单击的表单。使用

$(this).closest('.update-quantity-form').find('.cart-quantity').val()
从同一表格中获取数量

此外,您不应该在HTML元素中使用非标准属性
href
中无效,它仅用于
。要向元素添加特定于应用程序的数据,请使用
data XXX
属性,可以在jQuery中使用
.data()
方法访问这些属性

因此,将其更改为:

echo "<button data-id='{$id}' class='btn update-quantity' type='submit'>Update</button>";
echo“更新”;

然后使用
$(this.data('id')
而不是
$(this.attr('href')

非常感谢您的回答。它现在工作得很好。谢谢你的时间!祝你有愉快的一天/晚上!
$('.update-quantity-form').find('.cart-quantity').val()
$(this).closest('.update-quantity-form').find('.cart-quantity').val()
echo "<button data-id='{$id}' class='btn update-quantity' type='submit'>Update</button>";