Hi Team
I am unable to achieve this logic, where an input field as a number in the form, and when i refreshed its defaults to 2 and 1 than 0. When it's increased, it must be updated to the shopping cart and display a message to alert the user. I need some help to achieve this and I'm using php pdo, jquery, and HTML.
// php code
session_start();
require_once 'dbconn.php';
// add to cart
if(isset($_POST['product_id'])) {
$product_id = $_POST['product_id'];
if(isset($_SESSION['cart'][$product_id])) {
$_SESSION['cart'][$product_id]++;
} else {
$_SESSION['cart'][$product_id] = 1;
}
echo count($_SESSION['cart']);
exit;
}
?>
// jquery logic
// Listen for form submit event
$(document).ready(function(){
$('.add-to-cart-btn').click(function(){
var product_id = $(this).attr('data-product-id');
$.ajax({
url: 'add_to_cart.php',
method: 'post',
data: {
product_id: product_id
},
success: function(response){
$('#cart-count').text(response);
if(response == 1) {
$('#cart-message').show().text('1 item added to cart');
$('#basket-overview').removeClass('d-none');
}
}
});
});
});
// html code
2 Replies
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Tuhin PaulPosted Apr 19, 2023, 5:34 PM
In your HTML form, create an input field with type="number" and a default value of 2. You can use the "value" attribute to set the default value.
Using jQuery, listen for the "change" event on the input field. When the input value changes, send an AJAX request to your server to update the shopping cart with the new quantity. You can use the jQuery.ajax() method to send the request.
Rajkiran SwainPosted Apr 19, 2023, 4:42 PM
PHP code:
jQuery code:
HTML code: