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

Part 15- What is Repeater (Networking Devices)- Computer Networking- CCNA

Repeater  hello friends i am Vasu Birla and today i am starting new segment of CCNA computer networking  its a Networking Devices. we will discuss every important Devices used in networks. Repeater is a first networking devices. What is Repeater  Repeater is a device that receives signals and re-transmits by amplifying or regenerating signals. Repeater has two port one is for receive signals from previous network and second port is for retransmit signals to the next extended network. Two Port Repeater Repeater is a device which is used to Regenerate or replicate signal (Pichhe se aa rahe signal ko regenerate karke ya amplify karke aage strong signals bhej sakte he) Analog and digital both type of signals can be retransmitted by repeater. Here there is difference between regeneration and amplifying.  Amplification means , received signals will be amplified as it is , whether there are impurities in signals  and Regeneration means repeate...

GitHub Repo Collaboration Work on single project

 =============================================== To collaborate effectively with your friend on the same project, you should use Git branches to manage different lines of development. Here's a step-by-step procedure you can follow to streamline collaboration: 1. Create Separate Branches for Each Developer Create a New Branch for Your Friend: On your local repository, create a new branch for your friend. For example if your friend name is kilvish , if you want to create a branch named kilvish , you would run: make sure you would be on main branch already   command->  git checkout -b kilvish git push origin kilvish 2. Set Up Your Friend’s Environment( On your Friend's System )  at kilvish side  run ->  Clone the Repository (if not already done): If your friend hasn’t cloned the repository yet, they should do so: command ->  git clone https://github.com/Vasu-Birla/your-repo.git   // your your main clone line  Fetch All Bran...

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 t...