How do I add an item to the cart without the page reloading

So how do I do this? if I gotta use REST api how do I set it up? would really appreciate your help, thx!

link to the code:

https://gist.github.com/StackingUser/34b682b6da9f918c29b85d6b09216352

You seem to have gotten the fetching part, not sure if it works--but, essentially what you'll be needing to work on is called DOM manipulation.

It's the process of manipulating elements of your html through javascript.

Since you already know how to do fetch and then it's method then. You can put your code right inside your last ".then" code and place or map the response data to the corresponding elements that you would like to have house that said data.

Since you haven't provided an html code, I will just give you a sample

html
<body>
  <ul id="cart"></ul> <!-- this is where you populate your cart -->
</body>

js
fetch("URL OF THE REST API").then(res => { //where res is the response data
 let cart = document.querySelector('#cart'); // get ul element from html
 let item = document.createElemennt('li'); //create an li for the ul
 let img = document.createElement('img'); //image for the item/product
 let img.src = res.product_image; // let's say this is the product image
 let name = document.createElement('span'); // for the product name
 let name.innerHTML = res.product_name; // give name to element
 
 item.append(img);  // now place the img element inside the li
 item.append(name); // place the span element inside the li

 cart.append(item); // place the product item li inside the cart ul

 //now you don't have to reload the page, because they have been programmatically changed inside the dom via javascript.
});

// You can work things out the rest, just map out the data with a corresponding element, you can do (let span = document.createElement('span');) if you wanna make span, or div, or img, whatever your api needs.

Back to Top