I encountered an issue with loading an array from session storage in Java Script

I am struggling to restore and reuse a created array in HTML. I attempted using JSON, but it was not successful for me. In the code below, I am attempting to reload items that were previously stored in an array on another page. However, when I try to load them, it does not work. How can I resolve this issue? Do I need to include a header file for JSON? Thank you.

$( document ).ready(function() {
    var count=sessionStorage.getItem('items');      
)};

Answer №1

The feature of the sessionStorageproperty is that it grants access to a session Storage object specific to the current origin. The process involves both stringifying the object before storing it in the session, and parsing it when retrieving the data.

     var user = {'name':'John'};
     sessionStorage['user'] = JSON.stringify(user);
     console.log(sessionStorage['user']);
     var obj = JSON.parse(sessionStorage['user']);
     console.log(Object.keys(obj).length);

To see an example, visit this JSFiddle link. Keep in mind that opening a page in a new tab or window will initiate a new session. Learn more about session storage here.

Answer №2

One method to retain data when using sessionStorage is by converting arrays to strings before storing them and then parsing them back into arrays when retrieving the information.

var numbers = [1, 2, 3];
sessionStorage.setItem("numbers", JSON.stringify(numbers));
var storedNumbers = JSON.parse(sessionStorage.getItem("numbers"));

console.log(storedNumbers);

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

My current array is arr=[1,2,3,4]. I recently added an element to it using arr.push(5). Now I want to rearrange the array to be [5,4,3,2,1]. Any suggestions on how to achieve this

I currently have an array in the following format: var arr = [1,2,3,4] // Add another element to the array arr.push(5) // Now, arr = [1,2,3,4,5] I want to print my array as The elements in the array arr are: 5,1,2,3,4 When I use Arr.reverse(), it retu ...

I am looking to incorporate a new "ID" column into my mui data grid table in ReactJS that will incrementally count from 0 to the total number of rows

When displaying data from an API in a datagrid table component with multiple columns, it is necessary to include a column for the ID which should have values ranging from 0 to the number of rows. Currently, the Object_id is being displayed in this cell. T ...

I'm confused as to why I am only receiving one object entry in my fetch response instead of the expected list of entries

Is there a way to fetch all entries as a response instead of just one value? For example, when the next value returned by the fetch is {"next":"/heretagium"}, I can replace "/hustengium" with "heretagium" to get th ...

Struggling with implementing the use of XMLHttpRequest to transfer a blob data from MySQL to JavaScript

I have a blob stored in my local WAMP64/MySQL server that I need to retrieve and pass to an HTML file using XMLHttpRequest. I know I should set responseType="blob", but I'm not sure how to transfer the blob from PHP to JavaScript in my HTML file. Any ...

Establishing a link between numerous web browsers solely through client-side technology

After creating a compact AJAX-powered chat application, I wonder if it is feasible to handle all the communication client-side. Can individual pages recognize each other and share real-time updates without involving the server? Is there a way to achieve th ...

How to create XML using PHP with special characters?

Is it possible to create an XML file that includes special characters like "&", "=" and other invalid characters? I am struggling to find a solution. Is there a way to convert these characters or should I consider generating JSON instead? ...

performing functions concurrently within angularjs

I am currently utilizing angularjs 1.0 within my application. There is a dropdown on my cshtml page <select tabindex="2" id="Employee" ng-model="models.SelectedEmployee" ng-change="changeEmployee()" disabled="disabled" class="Answer" size="6"> < ...

After the introduction of ReactiveFormsModule, the functionality of the Angular router has ceased

I am working on setting up a reactive form in Angular for a login page. Here is my login form: <form [formGroup]="loginForm" (ngSubmit)="login(loginForm.value)"> <div class="form-group"> <label for="username">Username</label> ...

Footer div is being covered by the page

I am currently working on a website built with "WordPress", and I have implemented a mobile footer plugin that is designed to only appear on mobile devices. However, I am encountering an issue where the page content overlaps the footer on phones. I attemp ...

Issue encountered when trying to import an image URL as a background in CSS using Webpack

I have been trying to add a background image to my section in my SCSS file. The linear gradient is meant to darken the image, and I'm confident that the URL is correct. background-image: url(../../assets/img/hero-bg.jpg), linear-gradient(r ...

Retrieving data from a file results in receiving blank strings

Struggling to access the data within a directory of files, I've encountered an issue where the data doesn't seem to be read correctly or at all. Even though there is content when opening the files individually, when attempting to examine their co ...

Exploring the power of Angular by implementing nested ng-repeat functionalities:

I am currently working on an ng-repeat feature to add items from the array (album array). Everything seems to be functioning correctly. However, I also have a colors array that should assign different background-colors to the card elements of the album arr ...

The issue of AngularJS failing to bind object properties to the template or HTML element

Just dipping my toes into angularJS, following Todd Motto's tutorials, and I'm having trouble displaying object properties on the page. function AddCurrentJobs($scope){ $scope.jobinfo = [{ title: 'Building Shed', description: ...

Python - Error: Invalid JSON data with additional information

Having an issue aggregating data from multiple json files: path_to_json = 'generated_playlists/p1/' json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')] The format of the json files is as foll ...

JSON object containing elements with dash (-) character in their names

While I am in the process of parsing a `json` object, I encountered an element labeled as `data-config`. Here's an example: var video = data.element.data-config; Every time I attempt to parse this specific element, an error pops up: ReferenceError ...

Set the cookie to expire in 5 minutes using PHP, JavaScript, or jQuery

Is there a way to set a cookie in PHP that expires in 5 minutes? I am comfortable with the setcookie() function, but unsure about how to set the expiration time. Any explanation would be greatly appreciated. Could someone please guide me on how to achieve ...

What could be the reason for this XSS script not making a request to my server?

Currently diving into the realm of XSS attacks to enhance my knowledge on application security. My goal is to extract the user's cookie from a local website and then transmit it to my local server for testing purposes. I've successfully obtained ...

Issues arise with Highcharts Sankey chart failing to display all data when the font size for the series is increased

I am currently working with a simple sankey chart in Highcharts. Everything is functioning correctly with the sample data I have implemented, except for one issue - when I increase the font size of the data labels, not all the data is displayed. The info ...

Encountered an issue while processing the firebase get request with the following error message: 'Unauthorized request in Angular'

Here are my rules: Utilizing a Firebase database Calling an API URL from this section https://i.stack.imgur.com/auAmd.png I am attempting to retrieve data from a Firebase API in an Angular application, but I keep encountering an 'Unauthorized reque ...

How to access and retrieve data from a JSON file stored in an S3 bucket using Python

I have been tracking a JSON file stored in the S3 bucket test: { 'Details': "Something" } To retrieve and print the value of the key Details, I am using the following code snippet: s3 = boto3.resource('s3', ...