"Obtaining Data from Local Storage on a Different Page: A Step-by-

``How can I transfer JSON data stored in local storage from one page to another within the same domain?

In MainPage.html, the "user" data is stored in local storage and displayed. However, when data is added in AddEmploye.html and then returning to MainPage.html, the previous data is shown without the new additions.

What is a solution to overcome this issue? Thank you.


MainPage.html

<html>
<head>
 <meta charset="UTF-8"> 
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<style>
.header{
    background-color:black;
    position:relative;
    top:0;
    left:0;
    width:100%;
}
.header h1{
    color:white;
}
</style>
<body>

<div class="container-fluid">
    <div class="header">
        <h1>Employees</h1>
    </div>
    ...
    
</body>

</html>

AddEmploye.html

<html>
<head>
 <meta charset="UTF-8"> 
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<style>

.header{
    background-color:black;
    position:relative;
    top:0;
    left:0;
    width:100%;
}
.header h1{
    color:white;
}

...

</script>
<!--JavaScript -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

...

</body>
</html>

Answer №1

Solution

After reviewing the code in MainPage.html, I noticed a potential issue with the use of

localStorage.setItem("userData", Data);
. This could lead to data being overwritten instead of properly appended from AddEmploye.html. To address this, I added a check to see if userData already exists in localStorage before setting it, ensuring data is preserved.

It's important to note that using setItem will override existing data, similar to replacing an array entirely like var arr = [1]; arr = [2]; instead of adding elements individually like

var arr = []; arr.push(1); arr.push(2);
.

Edit

Your solution was almost there - just a small oversight! Mistakes happen to everyone, even the best of us. Don't worry, I made the necessary adjustments and hope this resolves your issue! :)

Edit 2

I've provided a solution for redirecting users to MainPage.html within AddEmployee.html below.

...

Edit 3

I've updated the function to delete rows in MainPage.html and retain the correct order of employees in localStorage. Test it out and let me know how it works for you!

...

Edit 4

After refining the JavaScript in MainPage.html, I came up with this enhanced version to handle pagination efficiently. It may need further testing, but give it a try and feel free to reach out if any issues arise. Your feedback is valuable for improvements!

...

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

Enable seamless SCSS inclusion in Vue components through automatic importing

My goal is to import a variables.scss file globally in my Vue project. I have set up my vue.config.js file as follows: module.exports = { css: { loaderOptions: { scss: { additionalData: `@import "@/st ...

Tips for resolving the error of encountering a forbidden and unexpected token in JSON at position 0 while using React hooks

const [forecastData, setForecastData] = useState({ forecast: []}); useEffect(() => { let ignore = false; const FETCHDATA = async () => { await fetch(forecast,{ headers : { ...

What is the best way to access the CSS font-size property using JavaScript?

I've attempted to adjust the font size using this code: document.getElementById("foo").style.fontSize Unfortunately, this code does not return any results. The CSS styles are all defined within the same document and are not in an external stylesheet ...

Is there a way for me to access the property value utilized in the Cypress test?

I am currently working on a Cypress example that can be found at the following link: : cy.get('[data-test-id="test-example"]') .invoke('css', 'position') .should('equal', 'static') Despite my ...

Setting minimum or maximum dates in jquery-simple-datetimepicker is proving to be challenging

Currently, I am utilizing the following library: In this jsfiddle example: http://jsfiddle.net/3SNEq/2/, everything works perfectly when setting minDate or MaxDate directly in the appendDtpicker method. However, when trying to use handleDtpicker like thi ...

Creating a JSON file by utilizing a for-each loop and Map - Wherein the value of the first element is duplicated in every iteration of the

When running the loop below, it is not adding all 6 values from the list. Instead, it just repeats the first value 6 times. Additionally, a Json file is created with the same inputs. Please note that despite referring to this helpful link, I am still unab ...

NextJS encountered a JavaScript heap out of memory issue

While developing my NextJs project, it suddenly encountered an unknown issue that resulted in the following error message being logged: <--- Last few GCs ---> [8728:000001A567CE5290] 8719226 ms: Mark-sweep (reduce) 1827.7 (1944.2) -> 1827.7 (189 ...

How can I trigger a page postback in ASP.NET after downloading a file?

Here is my current scenario: The user clicks on a LinkButton, triggering a PostBack on the page. However, I also need to initiate a file download for the user simultaneously. To achieve this, I added the following code to the LinkButton: lnkPrint.Attri ...

Tips for returning additional columns in a table when the JSON column is null in Oracle 12C using JSON_TABLE

In the database, there exists a table with a column that stores JSON data as CLOB: CREATE TABLE STUDENT ( NAME VARCHAR2(32 BYTE), ADDRESS VARCHAR2(30 BYTE), PAYMENT_JS CLOB ); ALTER TABLE STUDENT ADD CONSTRAINT CK_PAYMENT_JS CHECK ("PA ...

Displaying a List in Json Format Using C# MVC

Facing a challenge where I have a JSON list that needs to be formatted differently. Struggling to figure out why the formatting isn't coming out right. [{ "AppFormName": "TFB Test Application", "Questions": [{ ...

Display more/hide less form using div elements in a NextJS project

Looking to create a hidden block of amenities on my hotel website that can be expanded and collapsed with buttons in NextJS using tailwind-css. How can I achieve this functionality? Example 1: https://i.stack.imgur.com/BbrUj.png Example-2: https://i.stac ...

Is there a way to remove the initial word from a sentence?

Tue 26-Jul-2011 Looking to remove the initial word "Mon" using javascript with jQuery. Any suggestions on accomplishing this task? ...

Stop unauthorized access to php files when submitting a contact form

I have implemented a contact form on my HTML page that sends an email via a PHP script upon submission. However, when the form is submitted, the PHP script opens in a new page instead of staying on the current page where the form resides. I have tried usin ...

What is the behavior of a variable when it is assigned an object?

When using the post method, the application retrieves an object from the HTML form as shown below: code : app.post("/foo", (req, res)=> { const data = req.body; const itemId = req.body.id; console.log(data); console.log(itemId); }) ...

Achieving perfect alignment of an iframe on a webpage

Having an issue with aligning the iframe on my website. I have two buttons set up as onclick events that connect to internal pages displaying PHP data in tables within the iframe. Despite trying various CSS styles and positioning methods, I can't seem ...

Encountering an issue while constructing an Angular library project. The 'ng serve' command runs smoothly on local environment, but an error message stating

I recently developed an npm package called Cloudee. While it functions perfectly locally, I encounter an issue when attempting to deploy it. The error message states: 'Unexpected value 'CloudyModule in /home/hadi/dev/rickithadi/node_modules/cloud ...

display a different selection option depending on the previously chosen item

I'm working on displaying additional options in a select box when the user makes a selection from the main select box. I've set display:none for the select boxes, which will only appear when the user chooses an option from the main select box. C ...

What is the process for extracting the period value from SMA technical indicators within highcharts?

Can someone assist me in retrieving the period value from SMA indicator series by clicking on the series? series : [{ name: 'AAPL Stock Price', type : 'line', id: 'primary', ...

Expanding the size of an array list item in React

I have an array containing various currencies: const currencies =['USD','EUR','AUD','CNY','AED', 'AFN', 'ALL', 'AMD', 'ANG', 'AOA', 'ARS', 'A ...

Unveil Information with Underscore JS

I am attempting to showcase my data in a table using Underscore.js. Below is the div container class I am working with: <div id="container"></div> Upon window load, I have added an event listener: window.addEventListener("load", function(ev ...