I am creating an shopping page in which I have many Items that are displayed dinamically from database. I want to be able to add product in cart without refreshing the page, I want to know how to submit in javascript and be able to get that expecific data-id.
Normally I would just create a a href and pass product_id as a variable in the URL and then use php to manipulate the variable
<?php
$all_products = all_products();
echo '<div class="products">';
foreach($all_products as $key => $data){
echo '<div class="single-product">
<img src="'.$data['src'].'">
<h3>'.$data['name'].'</h3>
<h4>'.$data['price'].'</h4>
<button type="submit" class="addToCart" data-id="'.$data['product_id'].'">Add to cart</button>
</div>
';
}
echo '</div>';
?>
<script>
let addToCart = document.getElementsByClassName('addToCart');
addToCart.addEventListener("submit",(e)=>{
//let id = e.querySelector(data-id);
})
</script>
UPDATE
Thank you @M.Eriksson for your sugestion, I found online this, so if I replace the button with a href and pass javascript function add_to_cart() with product_id inside the variable I can access that variable in javascript using console.log, and I can get the id dinamically, however, I need to manipulate the id and send it using xmlhttpRequest, but it is giving status = 0, I dont see any mistakes in the sintax, and I used the same xmlhttpRequest in other page to request products from server and works
<?php
$all_products = all_products();
echo '<div class="products">';
foreach($all_products as $key => $data){
echo '<div class="single-product">
<img src="'.$data['src'].'">
<h3>'.$data['name'].'</h3>
<h4>'.$data['price'].'</h4>
<a ref="javascript:add_to_cart('.$data['product_id'].')">Add to cart</a>
</div>
';
}
echo '</div>';
?>
<script>
add_to_cart();
function add_to_cart(product_id=1){
console.log(product_id);
let form_data = new FormData();
form_data.append('product_id', product_id);
let url_data ="php/add_to_cart.php";
let ajax_request = new XMLHttpRequest();
ajax_request.open('POST', url_data);
let status1 = ajax_request.status;
console.log(status1);
ajax_request.onload = function(){
//console.log(ajax_request.responseText);
if(status1 == 200){
let output = JSON.parse(this.response);
//display product added sucessfully
let added_successfully = document.getElementById('added_successfully');
added_successfully.innerHTML=output['success'] ;
}
}
ajax_request.send(form_data);
}
</script>