Storing data locally and replacing the current URL with window.location.href

My course mate and I are working on writing a code that saves an order to local storage and redirects to an order page when the order button is clicked.

However, we are facing issues where clicking on the order button doesn't register in the application/local storage section of the Google Developer Tool and therefore does not redirect to a new page.

We added an event listener to display a console.log message when the button is clicked, just for troubleshooting purposes (this part is not critical).

We also used an online JavaScript validator to remove any typos or errors from our code.

Do we require any specific code on the order.html file to interact with local storage?

Answer №1

The problem at hand is that the DOMContentLoaded event is not triggering. To address this issue, I have opted to use the load event instead. For redirection purposes, I implemented the use of URL search params (due to lack of information about your other html file), but you can adjust it according to your specific needs.

Below is the code snippet

Please note: JavaScript will not execute on Stackoverflow and will display a securityError. To test this code, save it locally or use a platform like jsFiddle

function continue_ordering() {
  alert("Now continue with order");
};

window.addEventListener("load", function(e) {
  const orderButtons = document.querySelectorAll("button[data-order]");
  orderButtons.forEach(function(button) {
    button.addEventListener("click", function(e) {
      const btn = e.currentTarget;
      const container = btn.parentNode;
      const id = btn.getAttribute("data-order");
      const order = {
        id,
        title: container.querySelector(".title").innerText,
        price1: container.querySelector(".price").innertext,
        desc: container.querySelector(".desc").innerText
      };
      localStorage.setItem("order-" + id, JSON.stringify(order));
      window.location.search = "?ordering=true&order-id=" + id;
    });
  });
});
window.addEventListener("load", function(e) {
  if (window.location.search.search("ordering=true") != -1) {
    console.log("User is ordering");
    const params = new URLSearchParams(location.search)
    const id = params.get("order-id");
    if (!id || id == null) throw "There is no order id, error. Remove the ?ordering=true from the url and try again.";

    const order_info = JSON.parse(localStorage.getItem("order-" + id));
    if (!order_info) throw "Order information is not present: try ordering again. Remove the ?ordering=true from the url.";
    console.log("Order info is:\n", order_info);
    document.getElementById("ordering").removeAttribute("hidden");
    return;
  };
  document.getElementById("make-order").removeAttribute("hidden");
});
const orderButtons = document.querySelectorAll("button[data-order]");
orderButtons.forEach(function(button) {
  button.addEventListener("click", function(e) {
    console.log("The button was clicked.");
  });
});
<div id="make-order" hidden>
  <button data-order="test">Order</button>
  <div class="title">This is the title</div>
  <div class="price">130 USD</div>
  <div class="desc">Lorem</div>
</div>
<div id="ordering" hidden>
  <h1>
    You are ordering.
    <br> Choose
    <a href="javascript:location.search='';">Stop ordering</a> Or <a href="javascript:continue_ordering();">Continue with order</a>
  </h1>
</div>

Answer №2

Once the code tries to hook into it, the DOMContentLoaded event has already been triggered.

For more information on this topic, take a look at:

Code inside DOMContentLoaded event not working

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

Optimizing jQuery scripts by consolidating them to reduce file size

I've created a jQuery script that performs the same task but triggers on different events, including: Page load Dropdown selection change Clicking the swap button Typing in a text field However, I had to write separate scripts for each of these eve ...

Looking to display a page header alongside an image on the same page

I'm currently learning React.js and working on my very first app. As someone new to frontend development, I am aiming to have a header design similar to that of popular websites like StackOverflow or YouTube, where an image or icon is positioned just ...

Tips for populating several input fields using an ajax callback

I have a functioning code below that needs to update input fields with values retrieved from an ajax call. I am unsure about the ajax success function that would allow me to callback php variables ($first, $last, etc.) to populate those input fields. Your ...

How to create a basic calculator in AngularJS with two textboxes specifically designed for calculating squares?

My code snippet is as follows: <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> </head> <body> <div ng-app="app"> <div ng-controller="Calcu ...

Having difficulty with building a basic module in Node JS, it's just not cooperating

As a newcomer to Node JS, this platform, and the English language, I apologize in advance for any linguistic errors. I seem to be encountering a "return" error within my code. Specifically, when I include the hi.myFunc(); function, I receive the ...

Utilizing Packery.js in AngularJS

Having some trouble trying to integrate Packery.js with my angularjs app. It seems like they are not working well together. I tried setting isInitLayout to false, but no luck. This is the (bootstrap 3) HTML code I am using: <div class="row" class="js ...

Issue: [Issue: ENOENT: the file or directory './1695556319341.mp3' does not exist]

I am currently facing an issue while trying to convert an mp4 file to an mp3 file and then uploading it directly to Firebase storage without saving it locally on my machine. The error I encounter is "Error: [Error: ENOENT: no such file or directory, open ...

What is the process for customizing the color and thickness of the active tab inkBarStyle in React Material-UI?

Check out this inquiry: How can I change the color of the active tab in MUI? And for a potential solution, have a look at this response: The provided answer seems to be effective: <Tabs inkBarStyle={{background: 'blue'}}>... However, I a ...

Mastering the Art of Sending Multiple Values via Ajax

I'm having trouble passing multiple values using ajax in my code snippet. Here is the code I am working with: $(".ajax-button").change(function(event){ $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': '{{ ...

Creating Browser Extensions with Vue.js and Vue CLI

I am in the process of creating a Chrome Extension with a frontend powered by Vue.js. Everything was going smoothly using vuecli until my app started utilizing the Webextension-API. This API is only accessible to registered Extensions, not normal websites. ...

There is an issue with the format of the fromdate parameter in the JSON query. It should match the following format: "%Y-%m-%dT%H:%

Below is a snippet of JSON output I'm dealing with, specifically the LastAccessedDate value. This date format is provided by AWS CLI command and unfortunately, I cannot control its structure. { "MyList": [ { "Name": &qu ...

I encountered a PrimeVue error while running a Vue Jest test

When working on a Vue jest test, I encountered an error message "No PrimeVue Confirmation provided!" which seemed to be related to the useToast() and useConfirm() services. "transformIgnorePatterns": [ "<rootDir>/node_modules/(?! ...

Harvesting information from a Nested Array using Hive

Greetings! I am in search of a way to extract data from an array of arrays using Athena. create external table test ( customer string ) Location 'something-something' The contents of the single row in this table are as follows: select * from c ...

Is there a way to identify modifications in the DOM using jQuery UI Sortable?

My website is built using nodejs express and mongodb, and I am interested in integrating this library. I am curious about how I can detect changes in the order of elements to save their state. Should I use a form submission or jQuery functions? For exampl ...

Is it better to convert fields extracted from a JSON string to Date objects or moment.js instances when using Angular and moment.js together?

When working on editing a user profile, the API call returns the following data structure: export class User { username: string; email: string; creationTime: Date; birthDate: Date; } For validating and manipulating the birthDate val ...

Dividing JSON information into parts

I am attempting to present a highchart. I have utilized the following link: Highchart Demo Link Now, I am trying this web method: [WebMethod] public static string select() { SMSEntities d = new SMSEntities(); List<str ...

Tips on organizing and designing buttons within a canvas

let canvas = document.getElementById("canvas"); let context = canvas.getContext("2d"); // for canvas size var window_width = window.innerWidth; var window_height = window.innerHeight; canvas.style.background="yellow" canvas.wid ...

Transform JSON data into a CSV file using JavaScript or C# in an MVC4 framework, then import the data into

I am facing an issue with my website. Currently, when a user submits an application form, an email is sent. However, I would like to create a CSV file containing the form data and then automatically populate my database using this CSV file. Here is my ASP ...

Encountering an error stating "cloudinary.uploader is undefined" while attempting to delete media files from Cloudinary

I'm currently developing a web application using express and node.js. In my project, I'm utilizing cloudinary for uploading media files. While uploading and accessing media works smoothly, I'm encountering an issue with deleting images from ...

how can a select dropdown be dynamically displayed based on the previous selection?

If the first dropdown is set to "Professor" I want to display a second dropdown, but if it is set to "Student" then I do not want to display the second dropdown. function checkPrivilege() { var privilege = document.getElementById("permisija5").value; ...