0

My shopping cart is made in JavaScript. Everything works fine but not when I refresh the page then all I need is a way to make the items to be saved even when I refresh the page and not losing them.

Can I use localStorge for that if yes how? Or should I use mysql for that and if yes how?

you don't have to look at all my code I just need a way to make this thing possible.


if (document.readyState == 'loading') {
    document.addEventListener('DOMContentLoaded', ready)
} else {
    ready()
}

function ready() {

    $(".CheckOutButton").hide();
    var removeBtns = document.getElementsByClassName('cartRemovingBtn')
    for(var i=0; i<removeBtns.length;i++) {
        var removeButton = removeBtns[i]
        removeButton.addEventListener('click' , removeCartItem)
    }

    var addToCartBtns = document.getElementsByClassName('addToCartBtn')
    for(var i=0; i<addToCartBtns.length;i++) {
        var addToCartbtn = addToCartBtns[i]
        addToCartbtn.addEventListener('click' , addToCartClicked)

    }

}

function addToCartClicked(event) {
    var btn = event.target
    var shopItem = btn.parentElement
    var title = shopItem.getElementsByClassName('title')[0].innerText
    var price = shopItem.getElementsByClassName('price')[0].innerText
    var imgSrc = shopItem.getElementsByClassName('Fortnite-Packs-Img')[0].src
    addItemToCart(title, price, imgSrc)
    updateCartTotal()
}

function addItemToCart(title, price, imgSrc) {

    var item = document.createElement('div')
    var cartItems = document.getElementsByClassName('shopping-cart-items')[0]
    var cartItemNames = cartItems.getElementsByClassName('item-name')
    console.log(cartItemNames)
    for(var i = 0; i<cartItemNames.length; i++) {
        if (cartItemNames[i].innerText == title) {
            alert("This item already been added to cart.")
            return
        }
    }
    var cartItemLayout = `
        <div>
        <li class="itemInCart">
            <img class="item-img" src="${imgSrc}" alt="item1" />
            <span class="item-name">${title}</span>
            <span class="item-price">${price}</span>
            <span class="item-quantityword">Quantity: <span class="item-quantity item-quantityword">1</span></span>
            <button class="cartRemovingBtn"><span class="cartRemovingBtntxt">X</span></button>
            </li>
        </div>`
    item.innerHTML = cartItemLayout;
    cartItems.append(item)
    item.getElementsByClassName('cartRemovingBtn')[0].addEventListener('click', removeCartItem)

}


function removeCartItem(event) {
    // what ever button clicked on..
    var removeButtonClicked = event.target
    removeButtonClicked.parentElement.parentElement.remove()
    updateCartTotal()
}


function updateCartTotal() {
    var shoppingCartItems = document.getElementsByClassName('shopping-cart-items')[0]
    var cartItems = shoppingCartItems.getElementsByClassName('itemInCart')
    var itemsCount = cartItems.length
    var total = 0
    for(var i=0; i<cartItems.length;i++) {
        var cartItem = cartItems[i]
        var itemPrice = cartItem.getElementsByClassName('item-price')[0]
        var itemQty = cartItem.getElementsByClassName('item-quantity')[0]
        var price = parseFloat(itemPrice.innerText.replace('$', ''))
        var qty = itemQty.innerText

        total = (total + (price * qty)) *100 / 100 
    }
    document.getElementsByClassName('badge')[0].innerText = itemsCount
    document.getElementsByClassName('badge')[1].innerText = itemsCount
    document.getElementsByClassName('total-price')[0].innerText = '$' + total
    if (total > 0) {
        $(".CheckOutButton").show();
    } else {
        $(".CheckOutButton").hide();
    }

}



aynber
  • 22,380
  • 8
  • 50
  • 63
MRTN
  • 15
  • 7
  • Use localStorage or cookies. I would prefer [localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API). Yes, they can be changed using inspect, but the user is already supposed to be changing what is in the cart. – Yousername Dec 27 '19 at 19:46
  • Since cookies and localStorage are client-side, they can be tampered with. You may want to consider a server-side solution, such as a database. – Scott Marcus Dec 27 '19 at 19:49
  • 1
    Does this answer your question? [Persist variables between page loads](https://stackoverflow.com/questions/29986657/persist-variables-between-page-loads) –  Dec 27 '19 at 19:52
  • if tried to use localStorage but I don't really get it how it will be used on my cart, because when someone click add to cart button this will call a function that the innerHTML of the shopping cart item is here and here I should put the localStorge.setItem to get what the person clicked on and if I will get the item by localStorge.getItem outside the function and then set it equal to the innerHTML the innerHTML will be undefined because it's outside the function – MRTN Dec 27 '19 at 20:11

1 Answers1

0

You can use browser history's pushState and state.

let myCart = {};
function onLoad() {
  // set cart from state after load
  myCart = history.state || {};
}

function onCartChanged(updatedCart) {
  // push state in history whenever cart is changed
  history.pushState(updatedCart, 'cart');
}

With above you can get the current cart on refresh and also go back to previous cart with the browser's back.

Riddhesh
  • 571
  • 5
  • 18
  • Hey, in my project, where exactly should I put these? could you be more specific? appreciated. – MRTN Dec 27 '19 at 21:02
  • From your given code, I think contents of onLoad will goto your `ready` function, and onCartChanged will go to `updateSave`. You are trying to store the html in the localStorage, save(push) your cartItems array in history instead. – Riddhesh Dec 27 '19 at 21:07
  • ohmygod the updateSave shouldn't even be in my code i was trying the localStorge but it doesn't work.. I edited the code now. Can you check it again? thanks – MRTN Dec 27 '19 at 21:30
  • onCartChanged will go to your updateCartTotal that I'm sure. There depending on what you store, let's say cartItems. You'll get it in ready() on page load by using history.state, and from it, you need to recreate your html. – Riddhesh Dec 27 '19 at 21:55