Guest User

Guest User

  • Tech Writer
  • 2.1k
  • 465.4k

Invalid json data

May 17 2023 7:16 AM

Hi Team

I need some help with add to cart, its not updating but i get failed to add to cart on client side. On the server side, i am getting invalid json data. What am missing from my logic by looking at the front end side?

 

// html code

    <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  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="add_to_cart-1">
            <i class="fas fa-shopping-cart text-primary mr-1"></i>Add To Cart</a>
        </div>
    </div>
</div>

// jquery code
$(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) {

    const cartProps = JSON.stringify({id: productId, quantity: quantity });
    $.ajax({
      url: 'update-cart.php',
      type: 'POST',
      dataType: 'json',
      data: cartProps,
      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');
      }
    });
  }
});

// php code

<?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);
}
?>

 


Answers (1)