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');
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
$host = 'localhost';
$dbname = 'ecommerce_store';
$username = 'root';
$password = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id']) && isset($_POST['quantity'])) {
$id = $_POST['id'];
$quantity = $_POST['quantity'];
echo 'Received Data: ';
echo 'id: ' . $id . ', ';
echo 'quantity: ' . $quantity;
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("UPDATE cart SET quantity = :quantity WHERE id = :itemId");
$stmt->bindParam(':quantity', $quantity);
$stmt->bindParam(':itemId', $id);
$stmt->execute();
$response = ['success' => true];
echo json_encode($response);
exit;
} catch (PDOException $e) {
$response = ['success' => false, 'error' => $e->getMessage()];
echo json_encode($response);
exit;
}
} else {
echo json_encode(['success' => false, 'error' => 'Invalid request']);
}
} else {
echo json_encode(['success' => false, 'error' => 'Invalid request']);
}
?>
// 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();
$.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) {
if (response.success) {
var cartBadge = $('.fa-shopping-cart + .badge');
var cartCount = parseInt(cartBadge.text());
cartBadge.text(cartCount + 1);
} else {
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.');
}
});
});
});
// 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>