Retain the contents of the shopping cart even when the page is refreshed

For a course project, I am recreating a grocery store website and need assistance on how to retain the shopping cart values even after refreshing the webpage. Please inform me if more information is required...

       <button type="button" id="subtract" onclick="decrease()">-</button>
       <input class="quantity-box" type="text" id="text" value="0">
       <button type="button" id="add" onclick="increase()">+</button>
       <br>
      <button class="add-button" onclick="add(1)"><i class="fa fa-cart-plus"></i>&nbsp ADD TO CART</button>



<div class="cart">
      <h3 class="aisle-header">Shopping Cart</h3>
      <!-- list of the articles in the cart -->
      <ul id="items">
      </ul>
      <h3 id="total" style="text-align: right;">Total: 0 $</h3>
  </div> 
/* This script is to add increment and decrement quanity */
function decrease(){
var textBox = document.getElementById("text");
if (textBox.value > 0){
  textBox.value--;
  localStorage.setItem('quantity', textBox.value);
}
}

function increase(){
 var a = 1;
 var textBox = document.getElementById("text");
 textBox.value++;
 localStorage.setItem('quantity', textBox.value);
}

window.onload = function() {
var textBox = document.getElementById("text");
textBox.value = localStorage.getItem('quantity');
}


/* This script is to add quantity to cart */

      // Cost of all products in the cart
      var total = 0;
      // Index
      var i = 1;
      // List of the amount of every product in the cart
      var itemCost = [];
      // Add to cart
      function add(n){
          // Getting all Id of the selected shirt(brand ex: nike, price and quantity)
          brand = "name";
          priceId = "price";
          quantityId = "text";
          // Getting details of the selected shirt
          // brand
          name = document.getElementById(brand).innerHTML;
          // price
          price = document.getElementById(priceId).innerHTML;
          // quantity
          quantity = document.getElementById(quantityId).value;
          // Creating a li element to add it to ul
          var node = document.createElement("LI");
          // id of li element
          item = "item"+i;
          node.setAttribute("id", item)
          // cost of the selected shirt
          itemCost[i-1] = Number(price) * Number(quantity);
          // Updating the index i
          i += 1;
          // text of the li element
          var textnode = document.createTextNode(name+" "+quantity+" x $"+price+" ");
          // add the text to li element
          node.appendChild(textnode);
          // add li element to ul list
          document.getElementById("items").appendChild(node);

          total += Number(price) * Number(quantity);
          // update the total
          document.getElementById("total").innerHTML = "Total: " + total.toFixed(2) + " $";

          // Add a remove button
          document.getElementById(item).innerHTML += '<button class= "deleItem" onclick="deleItem('+"'"+item+"'"+')">X</button>';
          // you have to respect the order of: '' and ""

      }

      // Remove a product from the cart
      function deleItem(eId){
          document.getElementById(eId).remove();
          // slice is string method
          // eId (element Id) contain root + number (ex: item4)
          // n is the number in eId
          n = Number(eId.slice(-1)) - 1;
          // remove the cost of the product deleted from the cart
          total -= itemCost[n];
          // Updating the cost of products in the cart
          document.getElementById("total").innerHTML = "Total: " + total.toFixed(2) + " $";
      }

Note: Although I can utilize AJAX, I lack experience with it. Kindly provide a concise explanation if necessary. HTML/JAVASCRIPT/CSS/AJAX

Answer №1

Cookies are essential for various tasks, and you can easily utilize them with an array of items like in this sample code:

var cart = ['Orange', 'Grape', 'Kiwi'];
var json_str = JSON.stringify(cart);
setCookie('myCart', json_str, '30'); //This cookie will expire in 30 days

function setCookie(cname, cvalue, exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
  var expires = "expires="+d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

You can then retrieve the previously created cookie like so:

var json_str = getCookie('myCart');
var cart = JSON.parse(json_str);

function getCookie(cname) {
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for(var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

To view cookies, simply access Chrome DevTools (F12 key or Inspect), navigate to the Application tab, and find the Cookies item on the left menu.

Keep in mind that Chrome does not support cookies for local files, so if you want to store data locally, use the following method:

// Save data value
localStorage.setItem("name", "Alice");

// Retrieve data value
var name = localStorage.getItem("name");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging next-generation JavaScript (NextJS), incorporate sass-loader for seamless inclusion of variables in each individual

I'm having trouble implementing a custom webpack configuration in my nextjs project. My objective is to automatically import @import "src/styles/variables.scss"; for all scss files in my application. I have successfully set up a webpack con ...

Exploring the fundamentals of authentication with Express JS

Currently, I am encountering a challenge while attempting to implement basic authentication with Username and Password using Express JS. The problem lies in the fact that when I try to incorporate an if statement within an app.use() function, it does not s ...

Error in jQuery validation caused by a different value

I have a form on my website that needs to run some validations. One specific validation requires a file to be uploaded in order for a group of checkboxes to be selected. The issue I am facing is that the validations only seem to work when triggered, and b ...

Validation of forms in Angular using a pseudo submission method

On a webpage, there is a form with two buttons: one to calculate a price and the other to submit the form. Below is a basic example: <form novalidate name="formStep1"> <select ng-model="address" required> <option></option> ...

Ways to display or conceal dual views within a single Marionette js region

In my LayoutView, I have set up two regions: the filter region and the main region (Content Region). The main region displays a view based on the selection made in the filter region. Currently, I have a view for the main region called Current Year view. H ...

Generate a new array of objects by cloning an existing array of objects with placeholder values

I am looking to transform an array of objects into another array of objects in order to generate a graph. Below is the array I am using to determine the position of each object within the new object. let uniqueSkills = ['Using', 'Analyzing ...

Front Page Luma Design for Magento Platform

As a newcomer to Magento, I am currently using the Luma Home Page which appears blank. My goal is to incorporate an image that spans the entire browser viewport. Is it possible to achieve this through the admin panel by adjusting the CSS within the home pa ...

Instead of using colons, display the separation of hours, minutes, and seconds with underscores

Currently, I am utilizing moment.js to retrieve the present date and time with the intention of formatting it in the specific format below 'MMMM Do YYYY, h:mm:ss a' Unfortunately, the problem arises as the delineation between hours, minutes, and ...

Utilizing a captured group from a regular expression as a key in replacing a string

Looking for help understanding the behavior displayed in this NodeJS 12 console code snippet. I'm attempting to replace a portion of a string with the result from a capture group. While it does work, using that capture group result as a key in an obje ...

JavaScript - Assigning the same value to 2 properties but console log displays them as distinct values

While iterating through an array of documents, I am encountering a strange issue where setting two properties to the same value results in them having different values when logged using console.log. Here is the code snippet: this.logicItem.$promise.then( ...

Arrange four Divs next to each other with flexbox styling

I've been struggling with aligning my cards side by side. They are a series of divs nested in lists under a <ul> Changing the positioning is not resolving the issue, and I'm hesitant to alter the display as it's crucial for responsive ...

Is the indigo-pink color scheme fully implemented after installing @angular/material and scss using ng add command?

After running ng add @angular/material, we are prompted to choose a CSS framework and theme. I opted for indigo-pink and scss. Will the material components automatically inherit this theme, or do we need to take additional steps? When using normal CSS (wi ...

Experiment with erroneous scenarios using React, Jest, and React-Testing-Library

I've encountered an issue with a React component that triggers an Error when there is faulty programming. Specifically, the Component requires a prop called data, and I have the following code snippet in place to check for its existence: if (!data) { ...

React useEffect alert: Exceeding maximum update depth limit. Any solutions to bypass this issue?

In the code snippet below, I am utilizing the useEffect hook to monitor changes to a percentage variable and then initiating a timer to increment that variable every second. This process starts as soon as the page loads. The percentage variable is crucial ...

Ajax - Is utilizing API Endpoints the correct approach?

I am encountering an encoding issue when making an AJAX request to an API Endpoint. The code snippet below shows the Endpoint implementation using Java Spring: @Autowired ApiKeyRepository apiKeyRepository; @RequestMapping(value= "/weather/{cit ...

Changing the color variable of an object using an onClick function in JavaScript

I'm currently working on a simple game where users can draw using the keys W, A, S, and D. If you want to take a look at the progress I've made so far, here is a JSFiddle link. There's a collision function in the code that I no longer need, ...

Activate the POST HTTP method for a designated script on a shared hosting platform

Hey everyone, I'm looking to update some data in a script hosted on a shared platform. Both the access and destination files are PHP files. My goal is to access the external file through a POST operation, but I keep receiving a "501 Method not imple ...

The -webkit-background-clip feature seems to be malfunctioning in Safari

I am experiencing an issue where the code works perfectly on Chrome but fails to function properly on Safari. I have been unable to pinpoint the cause of this discrepancy and any assistance or insights would be greatly appreciated. For those interested, a ...

Implementing a Beveled Edge on a Shape using ThreeJS

I have put in a lot of effort to find the solution, but unfortunately I have not been successful so far. Currently, I am working on creating a shape using THREE.Shape, and I have the vertices data stored in a file. The shape appears to be straight without ...

Comparing scrollIntoView and moveToElement functions

When working with Selenium WebDriver, there are two primary methods to ensure an element is within the visible area: Scrolling into view: ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element); Using moveToElemen ...