Click here to Skip to main content
15,879,239 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Hi Team

I have this issue while debugging on the console tab, its says failed to fetch cart and update cart and causes server receives invalid json data. How can i solve this problem? Is it because what is on the html or cart table should be the same?

What I have tried:

PHP
<pre><?php

// Include your dbconn.php file that contains the PDO connection
$dsn = 'mysql:host=localhost;dbname=ecommerce_store';
$username = 'root';
$password = '';

try {
    // Create a new PDO instance
    $pdo = new PDO($dsn, $username, $password);

    // Set the error mode to exception
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Retrieve the JSON data from the request
    $data = json_decode(file_get_contents('php://input'), true);

    // Perform the necessary operations to update the cart in the database
    if (is_array($data)) {
        foreach ($data as $item) {
            $id = $item['id'];
            $quantity = $item['quantity'];

            // Update the cart item quantity in the database
            $stmt = $pdo->prepare("UPDATE cart SET quantity = :quantity WHERE id = :id");
            $stmt->bindParam(':quantity', $quantity);
            $stmt->bindParam(':id', $id);
            $stmt->execute();
        }

        // Return a success response
        $response = ['success' => true];
        echo json_encode($response);
    } else {
        // Return an error response if the JSON data is invalid
        $response = ['error' => 'Invalid JSON data'];
        echo json_encode($response);
    }
} catch (PDOException $e) {
    // Return an error response if there's a database connection issue
    $response = ['error' => 'Database connection error: ' . $e->getMessage()];
    echo json_encode($response);
}
?>



// 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>

HTML
<pre>    <div class="col-lg-4 col-md-6 col-sm-12 pb-1">
    <div class="card product-item border-0 mb-4" id="productId">
        <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="" id="product_img">
        </div>
        <div class="card-body border-left border-right text-center p-0 pt-4 pb-3">
            <h6 class="text-truncate mb-3" id="product_name">Colorful Stylish Shirt 0</h6>
            <div class="d-flex justify-content-center">
                <h6>R120.00</h6><h6 class="text-muted ml-2" id="price"><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">View Detail</a>
            <a href="#" class="btn btn-sm text-dark p-0 add-to-cart-btn" id="add_to_cart-1">
            ^__i class="fas fa-shopping-cart text-primary mr-1">Add To Cart</a>
        </div>
    </div>
</div>


// jquery code
/**
**/
<pre lang="Javascript">$(document).ready(function() {
  // Fetch and display the cart
  fetchCart();

  // Add event listener to the "Add To Cart" button
  $('.add-to-cart-btn').click(function(e) {
    e.preventDefault();
    var productId = $(this).attr('id').split('-')[1];
    addToCart(productId);
  });

  // Update the cart on quantity change
  $('.cart-quantity').change(function() {
    var productId = $(this).attr('data-productId');
    var quantity = $(this).val();
    updateCart(productId, quantity);
  });

  // Fetch the cart from the server
  function fetchCart() {
    $.ajax({
      url: 'fetch-cart.php',
      type: 'GET',
      dataType: 'json',
      success: function(response) {
        if (response && response.success) {
          renderCart(response.cart);
        } else {
          console.error('Failed to fetch cart');
        }
      },
      error: function() {
        console.error('Failed to fetch cart');
      }
    });
  }

  // Render the cart on the page
  function renderCart(cart) {
    var cartItems = '';
    var totalQuantity = 0;
    var totalPrice = 0;

    $.each(cart, function(index, item) {
      var rowTotal = item.price * item.quantity;
      cartItems += `
        <tr>
          <td>${item.product_name}</td>
          <td>${item.price}</td>
          <td>
            <input type="number" class="cart-quantity" data-productId="${item.id}" value="${item.quantity}" min="1">
          </td>
          <td>${rowTotal}</td>
        </tr>
      `;
      totalQuantity += parseInt(item.quantity);
      totalPrice += rowTotal;
    });

    // Update the cart badge
    $('.badge123').text(totalQuantity);

    // Update the cart table body
    $('#cart-table tbody').html(cartItems);

    // Update the total quantity and price
    $('#total-quantity').text(totalQuantity);
    $('#total-price').text(totalPrice);
  }

  // Add a product to the cart
  function addToCart(productId) {
    $.ajax({
      url: 'update-cart.php',
      type: 'POST',
      dataType: 'json',
      data: { id: productId, quantity: 1 },
      success: function(response) {
        if (response && response.success) {
          fetchCart();
          console.log('Cart updated');
        } else {
          console.error('Failed to update cart');
        }
      },
      error: function() {
        console.error('Failed to update cart');
      }
    });
  }

  // Update the quantity of a product in the cart
  function updateCart(productId, quantity) {
    $.ajax({
      url: 'update-cart.php',
      type: 'POST',
      dataType: 'json',
      data: { id: productId, quantity: quantity },
      success: function(response) {
        if (response && response.success) {
          fetchCart();
          console.log('Cart updated');
        } else {
          console.error('Failed to update cart');
        }
      },
      error: function() {
        console.error('Failed to update cart');
      }
    });
  }
});
Posted
Updated 19-May-23 2:01am

1 solution

Same question answered at Duplication of items in the cart when added[^]
 
Share this answer
 

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