Click here to Skip to main content
15,867,851 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi Team

I am stuck and need some help, basically the logic is when clicking add to cart button must add that item to the cart. The issue now when debugging on the server side i am getting 200 status but on the client side. Its giving me failed to add the item. What am i not doing write? I have the cart record on the database and has data.

What I have tried:

<?php

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

// Check if the AJAX parameter is present
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
    // 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']);
}
?>
PHP



// 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.');
      }
    });
  });
});
JavaScript



// html code
<div class="col-lg-3 col-6 text-right">
                       <a href="#" class="btn border">
                       class="fas fa-shopping-cart text-primary">
                        0
                        </a>
                        </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">class="fas fa-eye text-primary mr-1">View Detail</a>
            <a href="#" 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">Add To Cart</a>
        </div>
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900