Gcobani Mkontwana

Gcobani Mkontwana

  • 565
  • 1.9k
  • 407.5k

Cart is not updating when adding to cart

May 16 2023 2:04 PM

Hi Team

I need some help and been stuck to this issue, the issue when inspecting by debugging on the server side i am getting 200 status. But on the client side i am getting failed to add to item. What exactly am i doing wrong?

// client side code

     <div class="col-lg-3 col-6 text-right">
                            <a  class="btn border">
                            <i class="fas fa-shopping-cart text-primary"></i>
                             <span class="badge">0</span>
                             </a>
                             </div>


<div class="card-footer d-flex justify-content-between bg-light border">
            <a  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  class="btn btn-sm text-dark p-0 add-to-cart-btn" id="cart-1">
            <i class="fas fa-shopping-cart text-primary mr-1"></i>Add To Cart</a>
        </div>


// jquery code
$(document).ready(function() {
  $('.add-to-cart-btn').on('click', function(e) {
    e.preventDefault();

    var id = $(this).attr("id");
    var product_item = $("#product-item").val();
    var price = $("#price").val();
    var product_img = $("#product_img").val();
    var quantity = $("#quantity").val();
    // Send an AJAX request to update the cart in the database
    $.ajax({
      url: 'update-cart.php',
      method: 'POST',
      data: { id: id, product_item:product_item, price:price, product_img:product_img, 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.');
      }
    });
  });
});

// server side

<?php

error_reporting(E_ALL);
ini_set('display_errors', '1');

// Check if the AJAX parameter is present
if (isset($_SERVER['_X_REQUESTED_WITH']) && strtolower($_SERVER['_X_REQUESTED_WITH']) === 'xmlh...') {
    // Proceed with the AJAX request

    // Database connection details
    $host = 'localhost';
    $dbname = 'ecommerce_store';
    $username = 'root';
    $password = '';

    // Retrieve the product information from the AJAX request
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id']) && isset($_POST['quantity'])) {
        $id = $_POST['id'];
        $quantity = $_POST['quantity'];

        // Print the received data for debugging
        echo 'Received Data: ';
        echo 'id: ' . $id . ', ';
        echo 'quantity: ' . $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 or perform other operations
            // Example: Update the quantity in the cart table
            $stmt = $conn->prepare("UPDATE cart SET quantity = :quantity WHERE id = :itemId");
            $stmt->bindParam(':quantity', $quantity);
            $stmt->bindParam(':itemId', $id);
            $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
        }
    } else {
        echo json_encode(['success' => false, 'error' => 'Invalid request']);
    }
} else {
    echo json_encode(['success' => false, 'error' => 'Invalid request']);
}
?>

 


Answers (1)