Skip to main content

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>



Comments

Post a Comment

Popular posts from this blog

How to deploy NodeJS app on server with Apache2 and acess it with Server IP addresss - Node JS deploy project Live.

     hello friens , This is Vasu Birla , in previous post we have seen the deployement of NodeJS app on AWS instance server instance but AWS server is expensive than other servers . SO today we will use simple Ubuntu server for making Live out Project using Apache2 . At the end you will be abe to access your NodeJS app using server IP address from anywhere  .. 1.  Login to your server using SSH terminal . (in AWS part i already explained how to do this )     -> Open your putty in hostname put your server IP -      login with ssh username ->root and password     (if you dont have root username and pass ask your      provider or reset it from cpanel or hosting panel ) 2. after login - on terminal you can Put your project anywhere.     There are two ways to put your project folder on server location     (i) - > using Github - (very popular and easy to track your everyday code changes to your project folder)             you can push your entire project folder to git-hub and and

How to to deploy python app sepratly on same server (previous one ) /root/demo - Deploy Python app on Ubuntu Server using ssh Terminal - by Vasu Birla

hello friends , am Vasu Birla and Today we will deploy Python App.. in previous post we have deployed NODE js app on 0.0.0.0 (your server IP) and acess it using http://0.0.0.0/   Now  If you want to deploy a Python app separately on the same server, in the /root/demo directory, and access it using http://0.0.0.0/demo,  you can use Apache2 and mod_wsgi to host the Python app.   Additionally, you can configure Apache2 to proxy the requests for the   /demo path to your Python app without affecting the Node.js app hosted at the root.   First of all  put your python project folder on root location of server , using putty with cloning git repo or using FTP server and direct paste folder (in previous post we aleady discussed it)   lets suppose your folder name is demo .. location would be  /root/demo   install necessery things to support your python app .  like pip install or django ..etc     as well install in virtual enviorment also ..       -> python3 -m venv venv        -> source v

Part 19- Router (Networking Devices)- Computer Networking- CCNA

Hello friends...i am Vasu Birla and today will discuss about the most important Networking Device ..Router.  so let's start... ROUTER Router is a device which connect two or more networks together, which is why router is also known is Inter-networking device also. Inter-networking means two or more networks are connected together with the help of router. one more thing router is just like a computer  but it is designed for routing only, our computer can be router also but that are software router while hardware router which are specialize for routing is more efficient and fast than software router.  There is a Operating System installed on router which get moves data from one network to another network with the help of routing table.  Router does work on Network layer or Layer 3 of the OSI model.  Cisco Router There many companies which manufacture Router but main companies are - Cisco , Juniper , HP, 3com and Nortel  Functions of Router