How to add & remove items from Shopping Cart- Add to Cart - Remove From Cart - Node JS, Express js , Java Script
Suppose we have 3 Birthday Cakes in our database as a product - and we want to get item added & removed by customer -
Before adding into cart we have to show Products(cakes) to customer using following code -
Note - Create Your Own Roues, Controller & Models  and Import it here 
//UserRouter.js 
//Middleware to get cake list to send on menu.ejs
var Bcakes;
router.use("/menu",(req,res,next)=>{
    IndexController.fetchProducts({"catnm":"birthday cake"}).then((result)=>{
    Bcakes = result;
      next();
  }).catch((err)=>{
    console.log(err);
  });
})
router.use("/",(req,res,next)=>{
  IndexController.fetchProducts({"catnm":"birthday cake"}).then((result)=>{
  Bcakes = result;
    next();
}).catch((err)=>{
  console.log(err);
});
})
//============Middle Ware end ===============
import ProductSchemaModel from '../schema/ProductSchema.js';
//=middleare to fetch cake details 
var cDetails = [];
router.use("/shopcart/:_id",(req,res,next)=>{   
          console.log(req.params)
  ProductSchemaModel.find(req.params,(err,result)=>{
    if(result)
    {
          cDetails.push(result[0]) 
          var l = cDetails.length;
          //console.log(l)
    }
    else console.log(err)   
})
  next();
})
//IndexController.js  
fetchProducts(condition_obj)
{
  return new Promise((resolve,reject)=>{
   AdminModel.fetchProduct(condition_obj).then((result)=>{
     resolve(result);      
   }).catch((err)=>{
     reject(err);  
   });   
  });
}
//AdminModel.js  Note - Create Your Own ProductSchema 
fetchProduct(condition_obj)
{
 return new Promise((resolve,reject)=>{
   ProductSchemaModel.find(condition_obj,(err,result)=>{
     err ? reject(err) : resolve(result);        
   })    
 }) 
}
//IndexRouter.js  
router.get('/menu',(req,res)=>{
    res.render('menu',{"Bcakes":Bcakes,"Wcakes":Wcakes,"sunm":req.session.sunm})  // CakesDetails sent to menu.ejs page 
})
// Menu.ejs  in view foler of your Node Prodject 
<html>
// in Your Navigation Bar add Shopting Cart Icon/Image/Gif and whenever customer
 click on add to cart it should highlight on ICon 
  <div id="fetchcakes">
     <a href="/user/shopcart" class="nav-item nav-link" > <img src="../img/cart.gif" /> 
 <span class='cart-counter' style="  display:inline-block; width:20px; opacity:0; height:20px; background:red; text-align:center; border-radius:50%;  margin-left:10px;" >
    1</span>  
    </a>
 </div>
<% for(let row of Bcakes ) {%>   
    <div class="col-lg-6">
        <div class="d-flex h-100">
            <div class="flex-shrink-0">
                <img class="img-fluid" src="uploads/productsImages/<%- row.pimgname %>" alt="" style="width: 150px; height: 85px;">
                <h4 class="bg-dark text-primary p-2 m-0">₹ <%- row.price %></h4>
                <div class="card-body text-center mx-auto">
                    <div class='addtocart' >
                        <input type="hidden" id="addtocart" value="<%- row._id %>" >
                        <a href="/user/shopcart/<%- row._id %>" style="background-color: #212121; color: aliceblue;" class="btn cart px-auto" >ADD TO CART</a>
                    </div>
                </div>
            </div>
            <div class="d-flex flex-column justify-content-center text-start bg-secondary border-inner px-4">
                <h5 class="text-uppercase"><%- row.title %> </h5>
                <span> <%- row.description %> </span>
            </div>
        </div>
    </div>                            
    <%}%> 
</html>
<script>
     $(document).ready(function(){
            //create variable
            var counts = 0;
            $(".addtocart").click(function () {
            //to number and increase to 1 on each click
                    if(counts<5)
                    {
                        counts += +1;
                   }
                $(".cart-counter").animate({
            //show span with number
                            opacity: 1
                        }, 300, function () {
            //write number of counts into span
                            $(this).text(counts);
                        });
                    }); 
            });
</script>
After this when customer will click on Add to cart - following cart will be reflect 
now we have to click on this cart to open our Shopping cart with added items - 
//========== Add Item to Cart Finish here -   Now we have to remove it 
// addtocart.ejs file =  
<html>
<tbody id="cartitems">  
<% for(var i = 0; i < cDetails.length; i++) { %>
<tr>  
    <td>  
        <div class="row">  
            <div class="col-lg-2 Product-img">  
                <img src="../uploads/productsImages/<%- cDetails[i].pimgname %>" alt="..." class="img-responsive"/>  
            </div>  
            <div class="col-lg-10">  
                <h5 class="nomargin"> <b>  <%- cDetails[i].title %>  </b> </h5>  
                <p> <%- cDetails[i].description %>  </p>  
            </div>  
        </div>  
    </td>  
    <td> <strong > <%- cDetails[i].price %> </strong> </td>  
    <td data-th="Quantity" class='addtocart1' >
        <input type="hidden" id="pricecounter" value="<%- cDetails[i].price %>" >                             
        <b> <input type="number" id="qty"  class="form-control text-center" min="0" max="10" value="1"> </b>  
    </td>  
    <td> <strong class='cart-counter1' value="<%- cDetails[i].price %>" > <%- cDetails[i].price %> </strong> </td>  
    <td class="actions" id="deleteItem" data-th="" style="width:10%;">
        <input type="hidden" id="cakeId" value= "<%- cDetails[i]._id %>" >  
        <button onclick="removeFromCart('<%= cDetails[i]._id %>')" value= "<%- cDetails[i]._id %>"  class="btn btn-danger btn-sm"> <i class="fa fa-trash-o"> </i> </button>                               
    </td>
</tr>  
<% } %>       
</tbody>  
</html> 
<script>
//============= Delete Cart Item ============== 
function removeFromCart(_id){
    // alert(id);
    $.ajax({
                url: "/user/deleteItem/"+_id,
                type: "POST",
                data:{ _id : _id },
                dataType: 'json',
                    success: function(result) {
                        console.log(result)
                       window.location.href="/user/shopcart"
                    }
                }
    )
}
$(document).ready(function(){
            //============= Product Quantity Start ===========
            var priceCount = $('#pricecounter').val();
            //var qty = $('#qty').val();
            var counts = 0;
            $(".addtocart1").change(function () {
                var qty = $('#qty').val();
                $(".cart-counter1").animate({
                     opacity: 1
                        }, 300, function () {
                            $(this).text(priceCount*qty);
                        });
                    }); 
                //============= Product Quantity End ===========
            });
</script>

betpark
ReplyDeletetipobet
betmatik
mobil ödeme bahis
poker siteleri
kralbet
slot siteleri
kibris bahis siteleri
bonus veren siteler
YUR
canlı sex hattı
ReplyDeleteheets
https://cfimi.com/
salt likit
salt likit
LX8U
güngören
ReplyDeleteistanbul
fatih
adana
avcılar</a
4HX1