购物车添加商品失败,我该如何解决这个问题?

问题描述 投票:0回答:0

我有添加到购物车按钮,这个事件是使用 Ajax 调用发送请求到 php 添加到购物车。但是 ajax 调用无法添加到项目。我想知道如何解决这个问题?在数据库购物车表的记录中(Id、数量、总计、价格、折扣和产品名称)。

// html代码

    <div class="col-lg-4 col-md-6 col-sm-12 pb-1">
    <div class="card product-item border-0 mb-4">
        <div class="card-header product-img position-relative overflow-hidden bg-transparent border p-0">
            <img class="img-fluid w-100" src="img/product-1.jpg" alt="">
        </div>
        <div class="card-body border-left border-right text-center p-0 pt-4 pb-3">
            <h6 class="text-truncate mb-3">Colorful Stylish Shirt 0</h6>
            <div class="d-flex justify-content-center">
                <h6>R120.00</h6><h6 class="text-muted ml-2"><del>R120.00</del></h6>
            </div>
        </div>
        <div class="card-footer d-flex justify-content-between bg-light border">
            <a href="#" class="btn btn-sm text-dark p-0 view-details-btn" id="cart-0"><i class="fas fa-eye text-primary mr-1"></i>View Detail</a>
            <a href="#" class="btn btn-sm text-dark p-0 add-to-cart-btn" id="cart-123">
            <i class="fas fa-shopping-cart text-primary mr-1"></i>Add To Cart</a>
        </div>
    </div>
</div>`

// jquery 代码

$(document).ready(function() {
  $('.add-to-cart-btn').on('click', function(e) {
    e.preventDefault();
    
    var itemId = $(this).attr('id').split('-')[1];
    var productName = $(this).closest('.product-item').find('.text-truncate').text();
    var quantity = 1; // Set the desired quantity
    
    // Send an AJAX request to update the cart in the database
    $.ajax({
      url: 'update-cart.php',
      method: 'POST',
      data: { id: itemId, quantity: quantity },
      success: function(response) {
        // Handle the response from the server
        if (response.success) {
          // Update the cart badge count
          var cartBadge = $('.fa-shopping-cart + .badge');
          var cartCount = parseInt(cartBadge.text());
          cartBadge.text(cartCount + 1);
        } else {
          // Handle the error scenario
          alert('Failed to add item to the cart. Please try again.');
        }
      },
      error: function() {
        alert('An error occurred while processing your request. Please try again later.');
      }
    });
  });
});

// PHP 代码

ini_set('display_errors', 1);
error_reporting(E_ALL);
// Check if the AJAX parameter is present
if (isset($_POST['ajax']) && $_POST['ajax'] === 'true') {
    // Proceed with the AJAX request
    // Database connection details
    $host = 'localhost';
    $dbname = 'ecommerce_store';
    $username = 'root';
    $password = '';

    // Retrieve the updated quantity and item ID from the AJAX request
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id']) && isset($_POST['quantity'])) {
        $itemId = $_POST['id'];
        $quantity = $_POST['quantity'];

        try {
            // Connect to the database
            $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            // Update the cart item with the new quantity
            $stmt = $conn->prepare("UPDATE cart SET quantity = :quantity WHERE id = :itemId");
            $stmt->bindParam(':quantity', $quantity);
            $stmt->bindParam(':itemId', $itemId);
            $stmt->execute();

            // Return a success response
            $response = ['success' => true];
            echo json_encode($response);
            exit; // Stop executing further code
        } catch (PDOException $e) {
            // Return an error response
            $response = ['success' => false, 'error' => $e->getMessage()];
            echo json_encode($response);
            exit; // Stop executing further code
        }
    }
}

// Return an error response for direct access or invalid requests
$response = ['success' => false, 'error' => 'Invalid request'];
echo json_encode($response);
?>
php jquery shopping-cart
© www.soinside.com 2019 - 2024. All rights reserved.