[SOLVED] add to cart using javascript without refreshing the page


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

$all_products = all_products();
echo '<div class="products">';
      foreach($all_products as $key => $data){

          echo '<div class="single-product">
                      <img src="'.$data['src'].'">
                      <button type="submit" class="addToCart" data-id="'.$data['product_id'].'">Add to cart</button>

echo '</div>';

    let addToCart = document.getElementsByClassName('addToCart');
        //let id = e.querySelector(data-id);



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>
    let buttonsList = document.getElementsByClassName('addToCart');
    for (button of buttonsList) {
            fetch('/path/to/your/product/api?product_id=' + e.target.getAttribute('data-id')).then((data) => {
                 console.log('product added to cart!')

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.

people found this article helpful. What about you?