Get cart details javascript/ajax - cart drawer

PHOTO EMBED

Thu Oct 28 2021 10:14:17 GMT+0000 (UTC)

Saved by @JureVidmar #javascript #ajax




// ------------------ Cart drawer open/close  ----------------------\\
  $(document).on("click",".site-header__cart-ajax", function(e){
    e.preventDefault();
    $('body').toggleClass('drawer-open');
  });
  $('.cart-drawer__close').click(function(e){
    $('body').toggleClass('drawer-open');
  });
  $('.drawer-overlap').click(function(e){
    $('body').toggleClass('drawer-open');
  }); 

  $('.cart-drawer__continue').click(function(e){
    $('body').toggleClass('drawer-open');
  });





  $(document).on("click",".single-ajax-cart-btn", function(e){
    e.preventDefault()
      $(this).text('Adding...');
      $.ajax({
            type: 'POST', 
            url: '/cart/add.js',
            dataType: 'json', 
            data: $(this).parent().parent().serialize(),
            success: function(data) {
              $('.product-form__cart-submit').text('Add to cart');
              get_cart_details();
            console.log("submitted");
            },
            error: 'addToCartFail'
        });
  });

  
  $(document).on("click",".single-ajax-cart-btn-upsell", function(e){
    e.preventDefault()
    var upsell_form = $(this).parent();
      $(this).text('Adding...');
      $.ajax({
            type: 'POST', 
            url: '/cart/add.js',
            dataType: 'json', 
            data: $(upsell_form).serialize(),
            success: function(data) {
              $('.single-ajax-cart-btn-upsell').text('Add to cart');
              get_cart_details();
            console.log("submitted");
            },
            error: 'addToCartFail'
        });
  });

  $(document).on("click",".new-ajax-btn", function(e){
    e.preventDefault()
      $(this).text('Adding...');
      $.ajax({
            type: 'POST', 
            url: '/cart/add.js',
            dataType: 'json', 
            data: $(this).parent().parent().serialize(),
            success: function(data) {
              $('.product-form__cart-submit').text('Add to cart');
              get_cart_details();
            console.log("submitted");
            },
            error: 'addToCartFail'
        });
  });





var product_total_price = 0;

// ----------------- Get cart details -------------\\
function get_cart_details(){
  $.getJSON('/cart.js', function(cart) {
    // The cart data
    var drawer_item_html = '';              
    var cart_items = cart.items;
    var total_items = cart.item_count;
    product_total_price = cart.items_subtotal_price;
    console.log(product_total_price);
    $('.cart-drawer__total-amount').html('$'+((product_total_price * 0.01).toFixed(2)-20));
    console.log('total_items'+total_items);
    if(total_items == 0){
      $('.cart-drawer__no-item').addClass('cart-drawer__no-item_visible');
    }else{
      $('.cart-drawer__no-item').removeClass('cart-drawer__no-item_visible');
    }
    $('.cart-drawer__count').html(total_items);
    $('.cart-drawer__count--bag').html(total_items);
    $('.nav__cart-count').html(total_items);
    $('body').addClass('drawer-open');
    console.log(cart);
      for(var i=0; i<=cart_items.length; i++){
          var product_image = cart_items[i].image;
          var product_name = cart_items[i].product_title;
          var product_variant_option_name = cart_items[i].options_with_values[0].name;
          var product_variant_option_value = cart_items[i].options_with_values[0].value;
          var product_variant = cart_items[i].variant_title;
          var product_quantity = cart_items[i].quantity;
          var product_price = cart_items[i].line_price;
          var product_variant_id = cart_items[i].variant_id;
          var product_url = cart_items[i].url;
          var product_key = cart_items[i].key;
          
          // ------------- Add HTML item here -------------//
          drawer_item_html += '<div class="cart-drawer__item">';
          drawer_item_html += '<div class="cart-drawer__image">';
          drawer_item_html += '<img src="'+product_image+'" >';
          drawer_item_html += '</div>';
          drawer_item_html += '<div class="cart-drawer__info">';
          drawer_item_html += '<div class="cart-drawer__title"><a class="cart-drawer__url" href="'+product_url+'">'+product_name+'</a></div>';
        if(product_variant_option_value.indexOf("Default Title") != 0 ){
          drawer_item_html += '<div class="cart-drawer__variant">'+/*product_variant_option_name*/"Size/Color"+': '+product_variant_option_value+'</div>';
        }  
          drawer_item_html += '<div class="cart-drawer__price"  data-id="'+product_variant_id+'">$'+((product_price * 0.01).toFixed(2))+'</div>';
          drawer_item_html += '<div class="cart-drawer__qty">';
          drawer_item_html += '<button class="minus-btn cart-drawer__qty-btn" type="button" name="button"><i class="fa fa-minus"></i></button>';
          drawer_item_html += '<input type="number"  class="cart-drawer__qty-input" name="updates['+product_variant_id+']" data-id="'+product_variant_id+'"  id="updates_'+product_key+'" value="'+product_quantity+'" min="1" aria-label="Quantity" />';
          drawer_item_html += '<button class="plus-btn cart-drawer__qty-btn" type="button" name="button"><i class="fa fa-plus"></i></button>';
          drawer_item_html += '</div>';
          drawer_item_html += '</div>';
          drawer_item_html += '<div class="cart-drawer__remove">';
          drawer_item_html += '<a href="#" class="cart-drawer__remove-url" data-id="'+product_variant_id+'"><i class="fa fa-trash-o" aria-hidden="true"></i></a>';
          drawer_item_html += '</div>';
          drawer_item_html += '</div>';
          $('.cart-drawer__content').html(drawer_item_html);
          } 
      });     
}

// var discount_apply = '';
// var discount_status = '';

// $('.cart_discount_button').click(function(){
//     var my_inp = $('.disc_cont').val();
//     var my_discounts = $('.myDiscHolder').attr('data-disc');

//     if (my_discounts.indexOf(my_inp) >= 4){
//         discount_apply = my_inp;
//         discount_status = 'yes';
//         console.log(discount_apply);
//         $('.disc_cont').addClass('border-green');
//         $('.disc_cont').removeClass('border-red');
//     }else{
//         discount_status = 'no';
//         console.log('Bammer!! it did not matched');
//         $('.disc_cont').addClass('border-red');
//         $('.disc_cont').removeClass('border-green');
//     }
// });

// $('.button_checkout').click(function(e){
//     e.preventDefault();
//     if(discount_status == 'yes'){
//         window.location = '/checkout?discount='+ discount_apply;
//     }
//     else{
//         window.location = '/checkout';
//     }
// })



$('.button_checkout').click(function(e){
    window.location = '/checkout?discount=SPRING';
})











// ------------------ Ajax cart functions ----------------------\\
$(document).on("click",".minus-btn", function(e){
  e.preventDefault();
  var $this = $(this);
  var $input = $this.closest('div').find('input');
  var value = parseInt($input.val());  
  if (value > 1) {
    value = value - 1;
  } else {
    value = 0;
    $(this).parent().parent().parent().remove();
  }  
  $input.val(value);
  change_qty($input);
});

$(document).on("click",".plus-btn", function(e){    
  e.preventDefault();
  var $this = $(this);
  var $input = $this.closest('div').find('input');
  var value = parseInt($input.val());  
  if (value < 100) {
    value = value + 1;
  } else {
    value =100;
  }  
  $input.val(value);            
    change_qty($input);
});  

function change_qty($input){
  var variant_id= $($input).attr("data-id");
  var quantity= $($input).val();          
  var data = { updates: {} };
  data.updates[variant_id] = quantity;
  jQuery.ajax({
    type: 'POST',
    url: '/cart/update.js',
    data: data,
    dataType: 'json',
    success: function(res) {               
      console.log(res.items_subtotal_price);
      product_total_price = res.items_subtotal_price;
      var pro_data = res.items;              
      console.log(res);
      var price = res.total_price ;
      price = price/100 - 20;
      var tot_qty = res.item_count;
      if(tot_qty == 0){
        $('.cart-drawer__no-item').addClass('cart-drawer__no-item_visible');
      }else{
        $('.cart-drawer__no-item').removeClass('cart-drawer__no-item_visible');
      }
      $('.cart-drawer__count').html(tot_qty);
      $('.cart-drawer__count--bag').html(tot_qty);
      $('.nav__cart-count').html(tot_qty);
      $('.cart-drawer__total-amount').html('$' + price.toFixed(2));
      if(tot_qty == 0){
        $('.cart-drawer__total-amount').html('$0');
      }else{
        $('.cart-drawer__total-amount').html('$' + price.toFixed(2));
      }
      jQuery.each(pro_data, function(index, item) {
        var spe_price=item.final_line_price;
        spe_price= spe_price/100;
        if(item.id == variant_id){
          $('.cart-drawer__price[data-id='+item.id+']').html('$' + spe_price.toFixed(2));
        }
      });    
      
    }
  });
};

$(document).on("click",".cart-drawer__remove-url", function(event){
  event.preventDefault();
  var variant_id = $(this).attr('data-id');
  console.log("varient: "+variant_id);
  var data = { updates: {} };
  data.updates[variant_id] = '0';
  jQuery.ajax({
  type: 'POST',
  url: '/cart/update.js',
  data: data,
  dataType: 'json',
  success: function(res) {
  console.log(res);
  console.log(res.items_subtotal_price);
  product_total_price = res.items_subtotal_price;      
   var pro_data = res.items;
   var price = res.total_price;
    price = price/100 -20;
    var tot_qty = res.item_count;
    if(tot_qty == 0){
      $('.cart-drawer__no-item').addClass('cart-drawer__no-item_visible');
    }else{
      $('.cart-drawer__no-item').removeClass('cart-drawer__no-item_visible');
    }
    $('.cart-drawer__count').html(tot_qty);
    $('.cart-drawer__count--bag').html(tot_qty);
    $('.nav__cart-count').html(tot_qty);
    $('.cart-drawer__total-amount').html('$' + price.toFixed(2));
          if(tot_qty == 0){
        $('.cart-drawer__total-amount').html('$0');
      }else{
        $('.cart-drawer__total-amount').html('$' + price.toFixed(2));
      }
      if(tot_qty <= 0){
      $('.my__custom_cart_drawer').addClass('no_item');
    }
    
    var drawerDiscount = $(".cart-drawer__price").attr("data-id");
    console.log(drawerDiscount);
    

  
  }
  });
    $(this).parent().parent().remove();
  });


// ------------------ Ajax cart update for cart template ----------------------\\
$(document).on('change', '.cart__quantity-selector', function() {      
var variant_id= $(this).attr("data-id");
var quantity= $(this).val();      
var data = { updates: {} };
data.updates[variant_id] = quantity;
console.log(data);
jQuery.ajax({
type: 'POST',
url: '/cart/update.js',
data: data,
dataType: 'json',
success: function(res) { 
product_total_price = res.items_subtotal_price;
var pro_data = res.items;          
console.log(pro_data);
var price = res.total_price ;
price = price/100;
var tot_qty = res.item_count;
$('.new-cart-sidebar #bk-cart-subtotal-price').html('$' + price.toFixed(2));
$('.the_cart_total_amount').html('$' + price.toFixed(2));
$('.new-cart-sidebar .es-subtotal-text').html('Subtotal ( '+tot_qty+' Products):');
$('.the_cart_title').html(tot_qty+' item in your Cart');

jQuery.each(pro_data, function(index, item) {
  var spe_price=item.final_line_price;
  spe_price= spe_price/100;
  if(item.id == variant_id){
    $('.saso-cart-item-price.desk-price-ajax-change[data-id='+item.id+']').html('$' + spe_price.toFixed(2));
    $('.saso-cart-item-price.mob-price-ajax-change[data-id='+item.id+']').html('$' + spe_price.toFixed(2));
  
  }
});

}
});
//setTimeout(function(){ window.location.href="/cart"; }, 1000);
});




// ------------------ End of Ajax cart functions ----------------------\\
content_copyCOPY

Get cart details from the page using javascript, ajax -->cart drawer

pupnaps.com