Issue
This Content is from Stack Overflow. Question asked by Anderson Laurindo
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>
Solution
what i would do is to change the button type to button
aka: <button type="button">Button</button>
And after that change the EventListener to click and get the target from the event to access the data.
after which you can call a php script from javascript by using the fetch
function which will send a HTTP request to your backend server.
eg: (untested)
<button type="button" class="addToCart" data-id="some data">Add to cart</button>
<script>
let buttonsList = document.getElementsByClassName('addToCart');
for (button of buttonsList) {
button.addEventListener("click",(e)=>{
fetch('/path/to/your/product/api?product_id=' + e.target.getAttribute('data-id')).then((data) => {
console.log('product added to cart!')
})
})
}
</script>
Hope this helps 🙂
This Question was asked in StackOverflow by Anderson Laurindo and Answered by Sicet7 It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.