Append footer only once within a callback - javascript

My code is a bit complex as I'm appending dynamic content to a cart following a successful AJAX call. I need to add the footer ($(.mini-cart__footer)) to the cart only once at the end of the li items. How do I achieve that? The problem I'm currently facing that every time a li is added, a footer section is attached to it - so if 3 products are added to the cart, I'll end up with 3 footer sections.
Here is my code:
var __isp_options = {
isp_add_to_cart_callback: function(product_id) {
var image = ISP_PRODUCTS[product_id].image.replace('?c=2', '');
var title = ISP_PRODUCTS[product_id].l;
var description = ISP_PRODUCTS[product_id].d;
var price = ISP_PRODUCTS[product_id].p;
isp_add_to_cart(event, product_id);
var miniCart_html = '<div class="mini-cart__full is-mini-cart"><ul class="mini-cart__items is-cart__items"><li class="mini-cart__item"><div class="mini-cart__image-container"><svg class="icon icon-close"><use xlink:href="#icon-close"></use></svg><img class="mini-cart__image" src="'+image+'"></div><div class="product-meta"><span class="cart-item__brand">'+title+'</span><h2 class="product-meta__title">'+'1 X '+'<span class="product-meta__title cart-item__title product-tag">'+description+'<span class="dot"></span><span class="dot"></span></span></h2><span class="product-meta__price" data-money-convertible="">'+Shopify.formatMoney(price)+'</span></div></li></ul></div>';
$('.mini-cart__content').append(miniCart_html);
$('.is-cart__items').append('<footer class="mini-cart__footer"><div class="mini-cart__total"><span class="mini-cart__total-label">'+'Total'+'</span><span class="mini-cart__total-price" data-money-convertible="">'+Shopify.formatMoney(price)+'</span></div><form action="/cart" method="POST">'+'Continue to checkout'+'</form></footer>')
}
}
function isp_add_to_cart(event, product_id) {
$.ajax({
url: '/cart?view=mini-cart-content/add?id='+ product_id + "&quantity=1",
type: 'POST',
success: function(result) {
console.log('success');
$.getJSON('/cart.js').then(function(results) {
if (results['item_count'] > 0) {
$('.cart-icon-wrapper__count').text(results['item_count']);
$('.cart-icon-wrapper--has-items').show();
$('.cart-icon-wrapper--empty').hide();
}
});
},
error: function(result) { console.log('error'); }
});
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
return false;
}

Related

Changing Button Text based on the button clicked - not all buttons

I am trying to change the text of the button clicked, using beforeSend and Complete in an ajax function, changing the text from Add to Cart > Adding... > Added to Cart, but the text is changed in all buttons, not sure how to target the button clicked.
HTML - the button text is wrapped in a space with data attributes
<span class="js-btn-cta" data-addbtn="{{ btn_txt }}" data-soldout="{{ btn_txt_soldout }}" data-offerbtn="{{ btn_txt_selling }}" data-adding-cart="{{ btn_adding }}" data-added-cart="{{ btn_added }}">
JS - I am then changing the text before the request is sent and once complete using the following methods;
//START AJAX API ADD TO CART FUNCTION
let miniCartContentsSelector = '.js-mini-cart-contents';
let addingCartBtn = $('.add-to-cart-button');
let addingCartText = $('.js-btn-cta');
let ajaxify = {
onAddToCart: function(event){
event.preventDefault();
$.ajax({
type: 'POST',
url: '/cart/add.js',
data: $(this).serialize(),
dataType: 'json',
beforeSend: function(e) {
//Update btn text on product and collection pages
dataAddingCart = addingCartText.attr('data-adding-cart'),
addingCartText.text(dataAddingCart);
},
complete: function(e) {
//Update btn text on product and collection pages
dataAddedCart = addingCartText.attr('data-added-cart'),
addingCartText.text(dataAddedCart);
},
success: function(){
ajaxify.onCartUpdated();
currencyPicker.setCurrencyText();
},
error: ajaxify.onError
});
shippingBar.update();
},
onCartUpdated: function() {
$.ajax({
type: 'GET',
url: '/cart',
context: document.body,
success: function(context){
let
$dataCartContents = $(context).find('.js-cart-page-contents'),
$dataCartContentsPrice = $(context).find('.js-total'),
dataCartHtml = $dataCartContents.html(),
dataCartItemCount = $dataCartContents.attr('data-cart-item-count'),
dataCartItemTotal = $dataCartContentsPrice.attr('data-cart-item-total'),
$miniCartContents = $(miniCartContentsSelector),
$cartItemCount = $('.js-cart-item-count'),
$closeIcon = $('.js-close-cart'),
$cartItemTotal = $('.js-cart-item-total');
$cartItemCount.text(dataCartItemCount);
$cartItemTotal.html('<span class="money">' + dataCartItemTotal + '</span>');
$miniCartContents.html(dataCartHtml);
//change currency in cart when changed
currencyPicker.setCurrencyText();
Currency.convertAll(shopCurrency, Currency.currentCurrency);
if (parseInt(dataCartItemCount) > 0){
ajaxify.openCart();
$('.js-minus').prop("disabled", true);
}
else {
ajaxify.closeCart();
}
//close the cart drawer when clicking on x in cart header
function closeClick(event){
$('body').removeClass('show-sidebar');
console.log('close icon btn clicked');
}
//end close the cart drawer when clicking on x in cart header
//call the closeClick function
$('.js-close-cart').click(closeClick);
//end call the closeClick function
}
});
//reset pdp qty value to 1 once add to cart has been clicked
$(".js-quantity-field-pdp").val("1");
shippingBar.update();
ajaxify.closeModal();
},
onError: function(XMLHttpRequest, textStatus){
let data = XMLHttpRequest.responseJSON;
alert(data.status + ' - ' + data.message + ': ' + data.description);
},
openCart: function(){
let isInCartPage = window.location.href.indexOf('/cart') === -1;
if(isInCartPage) {
$('body').addClass('show-sidebar');
}
},
closeCart: function(){
$('body').removeClass('show-sidebar');
},
closeModal: function(){
$('.modal').modal('hide');
$('.modal-backdrop').modal('hide');
},
onCartButtonClick: function(event){
event.preventDefault();
//If the body has a class of show-sidebar, return TRUE.
let isCartOpen = $('body').hasClass('show-sidebar');
let isInCart = window.location.href.indexOf('/cart') === -1;
if(!isInCart) {
if(!isCartOpen) {
ajaxify.openCart();
}
else {
ajaxify.closeCart();
}
}
},
init: function(){
$(document).on('submit', addToCartFormSelector, ajaxify.onAddToCart);
$(document).on('click', '.js-menu-toggle active', ajaxify.onCartButtonClick);
$(document).on('click', '#mini-cart .js-keep-shopping', ajaxify.onCartButtonClick);
}
};
//initiate the function
ajaxify.init();
The problem is it changes button text for other buttons not clicked.
Thanks
You get all button with class "js-btn-cta" and you change the text attribute to all button with this class. Not only the action button.
Inside onAddToCart, you have to get the clicked button.
onAddToCart: function(event){
var clickedButton = $(this);
event.preventDefault();
$.ajax({
type: 'POST',
url: '/cart/add.js',
data: $(this).serialize(),
dataType: 'json',
beforeSend: function(e) {
//Update btn text on product and collection pages
dataAddingCart = clickedButton.attr('data-adding-cart'),
clickedButton.text(dataAddingCart);
},
complete: function(e) {
//Update btn text on product and collection pages
dataAddedCart = clickedButton.attr('data-added-cart'),
clickedButton.text(dataAddedCart);
},

Asp.net webform infinity scroll

I have a page shows product catalog populated by a webmethod.
When user click on image he is redirect to details page.
When user come back to catalog id like page scroll bottom at the product visited
How can i accomplish this
my html
<div class="articoli">
</div>
my javascript
<script>
$(document).ready(function () {
var Skip = 9;
var Take = 9;
function Load(Skip, Take) {
$('#divPostsLoader').html('<img src="Images/loading.gif" height="100" />');
$.ajax({
type: "POST",
url: "page.aspx/LoadProduct",
data: "{ Skip:" + Skip + ", Take:" + Take + " }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data != "") {
//accodo dati a div
$('.articoli').append(data.d);
}
$('#divPostsLoader').empty();
},
error: function () {
alert('error');
}
})
};
$(window).scroll(function () {
if ($(window).scrollTop() == ($(document).height() - $(window).height())) {
Load(Skip, Take);
Skip = Skip + 9;
}
});
});
my c# webmethod
[System.Web.Services.WebMethod]
public static string LoadProduct(int Skip, int Take)
{
StringBuilder GetProduct = new StringBuilder();
MyDataBaseEntities db = new MyDataBaseEntities();
var prod = (from a in db.TAB
select a).Skip(Skip).Take(Take);
foreach (var a in prod)
{
var Codart = a.Codart;
var Prezz = a.Prezz;
var pathimg = a.pathimg;
GetProduct.Append("<div class=\"col-md-4\">");
GetProduct.Append("<div class=\"col-md-6 text-left\">");
GetProduct.AppendFormat(string.Format("<a href='Details.aspx?Articolo={0}' class=\"codart\" >", Codart));
GetProduct.AppendFormat("<span class=\"codart\">{0}</span>", Codart);
GetProduct.Append("</a>");
GetProduct.Append("</div> ");
GetProduct.Append("<div class=\"col-md-6 text-right\" style=\"color:gray;font-size:large;\">");
GetProduct.AppendFormat(string.Format("{0:c}", Prezz));
GetProduct.Append("</div> ");
GetProduct.AppendFormat(string.Format("<a href='Details.aspx?Articolo={0}' class=\"codart\" >", Codart));
GetProduct.AppendFormat(string.Format("<img src='{0}' class='img-responsive MyImage' alt='{1}'/>", pathimg, Codart));
GetProduct.Append("</a>");
GetProduct.Append("</div> ");
}
return GetProduct.ToString();
}
how can i scroll bottom at page load?
Try adding an Id to the item(s) you want to scroll to. You can then, depending on how you want to tackle it, either href or assign said Id through a script to initiate a scroll. Here you can see more details on how to scroll to a specific part of your page by using the component's Id.
I would add a unique Id to each item in your list.
Then I would write a script to read/set a variable to which item to scroll to.
Mind you, I'm writing this on a whim so you might need to correct or alter it to fit your needs.
You can use this to save and read cookies with jquery.
The script could be something like this:
var scrollToId;
$(document).ready(function () {
var cookie = $.cookie('last_clicked_id');
if (cookie != '') {
scrollToId = cookie;
} else {
scrollToId = '#';
}
$("html, body").animate({ scrollTop: $(scrollToId).offset().top }, 1000);
});
$('.productItemClass')
.on('click',
function() {
$.cookie('last_clicked_id', $(this).attr('id'));
});
use this and set the variable sc
var sc;
var scroll;
var loop = setInterval(function() {
sc = window.scrollTop;
if (scroll === null) {
localstorage.setItem("bgc", sc);
}
}, 10);
window.onload = function() {
scroll = localstorage.getItem("bgc");
if (scroll !== null) {
window.scollTop = scroll + "px";
}
}

AJAX list update, get new elements and count

I have this HTML list
<ul id='usernameList'>
<li class='username'>John</li>
<li class='username'>Mark</li>
</ul>
and a form to add new names via AJAX, multiple add separated by commas. The response is a list with the names
[{name:David, newUser:yes}, {name:Sara, newUser:yes}, {name:Mark, newUser:no}]
I'm trying to insert this names sorted alphabetically in the list, like this example https://jsfiddle.net/VQu3S/7/
This is my AJAX submit
var form = $('#formUsername');
form.submit(function () {
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
dataType: "json",
beforeSend: function () {
//
},
success: function (data) {
var listUsernames = $('#usernameList');
var numUsernames = listUsernames.children().length;
$.each(data, function(i, user) {
if(user.newUser == "yes"){
var htmlUser = "<li class='username'>" + user.name + "</li>";
var added = false;
$(".username", listUsernames).each(function(){
if ($(this).text() > user.name) {
$(htmlUser).insertBefore($(this));
added = true;
}
});
if(!added)
$(htmlUser).appendTo($(listUsernames));
}
// HERE I DO alert('numUsernames')
// I get the same number of users before sending form
// How can I update here the value of listUsernames and numUsernames?
});
}
});
return false;
});
My question is, how I can update the value of listUsernames and numUsernames after adding an item?
You just need to update numUsernames at that point.
Add this where your comments are:
numUsernames = listUsernames.children().length;
listUsernames already has the updated children, as it's a reference to the parent element.
Edit: Re: your comment below:
This should probably work:
$(".username", listUsernames).each(function(){
if ($(this).text() > user.name) {
$(htmlUser).insertBefore($(this));
added = true;
return false; // stop `.each` loop.
}
});
First you don't need a double jQuery wrapping:
$(htmlUser).appendTo($(listUsernames));
listUsernames is already a jQuery object, so try:
$(htmlUser).appendTo(listUsernames);
And after every adding, you can update the numUsernames variable with:
numUsernames = listUsernames.children().length;
but this is not necessary because you can always access listUsernames.children().length in the success handler.
I update your JSFiddle
var listUsernames = $('#usernameList');
var numUsernames = listUsernames.children().length;
var data = [{name:'David', newUser:'yes'}, {name:'Sara', newUser:'yes'}, {name:'Mark', newUser:'no'}]
$.each(data, function(i, user) {
if(user.newUser == "yes"){
var htmlUser = "<li class='username'>" + user.name + "</li>";
var added = false;
$(".ingredient", listUsernames).each(function(){
if ($(this).text() > user.name) {
$(htmlUser).insertBefore($(this));
added = true;
}
});
if(!added)
$(htmlUser).appendTo($(listUsernames));
}
// HERE I DO alert('numUsernames')
// I get the same number of users before sending form
// How can I update here the value of listUsernames and numUsernames?
});

How to send JSON object list to light box?

In MVC 4 application I want when click a link, to show some related Products list in lightbox. I have method returns products I need:
public ActionResult GetRelatedProducts(int id)
{
var realProducts = GetRelatedProducts(id);
List<object> productsObjectList = new List<object>();
foreach (var item in realProducts)
{
productsObjectList .Add(new
{
id = item.Id,
fullname = item.Name
});
}
return Json(productsObjectList , JsonRequestBehavior.AllowGet);
}
HTML is:
<a class="show" id="show">Show</a>
<div id="productBox" style="display: none;">
// Product list will get here
</div>
And script:
$('#show').click(function (e) {
url = '#Url.Action("GetRelatedProducts", "Product")';
var data = { id: '#Model.Id' };
$.post(url, data, function (result) {
$('#productBox').lightbox_me({
onLoad: function () {
//How to send returned product list to light box, to show them by foreach loop
}
});
e.preventDefault();
});
});
How can I send product list to productBox to show products?
You code:
$('#show').click(function (e) {
url = '#Url.Action("GetRelatedProducts", "Product")';
var data = { id: '#Model.Id' };
$.post(url, data, function (result) { // <- "result" will contain array
$('#productBox').lightbox_me({
onLoad: function () { ... }
});
e.preventDefault(); // <- this must prevent "a" tag, put it outside
});
});
You could use your list on client side like this:
$.post(url, data, function (result) {
var list = '<ul>';
for(var i = 0; i < result.length; i++)
{
list += '<li>' + result[i].fullname + '</li>';
}
list += '</ul>';
$('#productBox').html(list).lightbox_me();
});
OR as Vladimir Bozic wrote, just use PartialViewResult, from controller return PartialView, it is like normal view, but without layout, just html block and you can use it like:
$.post(url, data, function (result) {
$('#productBox').html(result).lightbox_me();
});

ajax based multiple dropdown showing result with pagination

have 3 drop-down
select#opt-category,select#opt-sector,select#opt-company
category onchange
$("select#opt-category").change(function () {
category = $(this).val();
if(sector!='')sector='';
if(company!='')company='';
$("#opt-sector").load('menus.php?category='+category);
$("#opt-company").load('menucmp.php?category='+category);
});
will load sector and company based on category and result shown as
$(".showgrid").load('portal.php?category='+category+'&sector='+sector+'&company='+company);
the results are based on paging which also called ajax
function loading_show(){
$('#loading').html("<img src='assets/img/ajax-loader.gif'/>").fadeIn('slow');
}
function loading_hide(){
$('#loading').fadeOut('slow');
}
function loadData(page,category){
loading_show();
$.ajax
({
type: "POST",
url: "pagination_data.php",
data: {'page':page,'category':category},
success: function(msg)
{
$("#container").ajaxComplete(function(event, request, settings)
{
loading_hide();
$("#container").html(msg);
});
}
});
}
loadData(1,<?php echo $catgory?> ) // For first time page load default results
$('#container .pagination li.active').live('click',function(){
var page = $(this).attr('p');
var category= $(this).attr('q');
loadData(page,category);
});
$('#go_btn').live('click',function(){
var page = parseInt($('.goto').val());
var category = parseInt($('.total').attr('b'));
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(page,category);
}else{
alert('Enter a PAGE between 1 and '+no_of_pages);
//$('.goto').val("").focus();
return false;
}
});
when category dropdown changed, it loads the new value on other dropdown but can't load the result into .showgrid.
is there another way to accomplished this task

Categories

Resources