Saving information on localStorage is not possible

Recently, I created a demo for a basic Login and Logout application that utilizes an access token. If a user attempts to access another page without logging in (meaning the access token is null), they are redirected back to the Login page. Initially, I used sessionStorage to store the user token and everything worked smoothly. However, when I switched to using localStorage instead, my application ceased functioning properly. Although the login process still completes successfully, there is a brief moment where I am redirected back to the Login page as if the token was not saved at all. Subsequently, even after generating a new token post-login, it seems like there is an issue specifically related to localStorage.

Update: Upon further investigation, it appears that both storage methods do save the token, but I encountered difficulties passing it to other pages when using localStorage.

This is a snippet of code from my Login Page:

$('#btnLogin').click(function () {
            $.ajax({
                url: '/token',
                method: 'POST',
                contentType: 'application/json',
                data: {
                    userName: $('#txtFullname').val(),
                    password: $('#txtPassword').val(),
                    grant_type: 'password'
                },
                // Upon successful login, store the token in localStorage
                success: function (response) {
                    //sessionStorage.setItem("accessToken", response.access_token);
                    localStorage.setItem("accessToken", response.access_token);
                    window.location.href = "User.html";
                    //$('#divErrorText').text(JSON.stringify(response));
                    //$('#divError').show('fade');
                },
                // Display any errors in the Bootstrap alert <div>
                error: function (jqXHR) {
                    $('#divErrorText').text(jqXHR.responseText);
                    $('#divError').show('fade');
                }
            });
        });

This part shows the base code from another page:

if (localStorage.getItem('accessToken') == null) {
            window.location.href = "Login.html";
        }

Answer №1

Is it guaranteed that response.access_token will never be null?

You can verify this using the Chrome development tools (Windows: Ctrl + Shift + i or macOs: command + option + i)> Application > Storage > Local Storage:

https://i.sstatic.net/kEMN2.png

As depicted in the image, the value may indeed be set to null.

I trust this information proves helpful.

Answer №2

localStorage is designed to store only string values. It is possible that the value of response.access_token may not be a string. In this case, you can try the following approach:

localStorage.setItem("accessToken", JSON.stringify(response.access_token));

When you need to retrieve the stored data, you can use:

JSON.parse(localStorage.getItem("accessToken"))

Answer №3

To save an object in local storage, you can use the following method (demonstrated in a StackOverflow post):

var testObject = { 'one': 1, 'two': 2, 'three': 3 };

// Store the object in local storage
localStorage.setItem('testObject', JSON.stringify(testObject));

// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');

console.log('retrievedObject: ', JSON.parse(retrievedObject));

You can implement this in your code like so:

$('#btnLogin').click(function () {
            $.ajax({
                url: '/token',
                method: 'POST',
                contentType: 'application/json',
                data: {
                    userName: $('#txtFullname').val(),
                    password: $('#txtPassword').val(),
                    grant_type: 'password'
                },
                // Upon successful login, store the token in sessionStorage
                success: function (response) {
                    var obj= { 'accessToken': response.access_token};
                    localStorage.setItem(JSON.stringify(obj));
                    window.location.href = "User.html";
                },
                // Show any errors in the Bootstrap alert <div>
                error: function (jqXHR) {
                    $('#divErrorText').text(jqXHR.responseText);
                    $('#divError').show('fade');
                }
            });
        });

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

What is the optimal location for storing JSON data while dynamically loading via AJAX?

Let's imagine a scenario where there is an HTML page hosting a dynamic modal box. Clicking on different links within the page triggers the modal to open, each showing different content based on the clicked link. The dialog contents are fetched using A ...

What is the best way to toggle a specific div element within an ng-repeat loop?

I have a list of products. When I click on a product, it should be added to the database. If I click on the same product again, it should be removed from the database. I am toggling the wishlistFlag using ng-click. This works correctly for one div element, ...

The PHP Comet feature is causing the page to experience delays in reloading

Hello, I am working on implementing comet functionality using PHP and jQuery. The comet starts with every page load, but this seems to be causing a significant delay in loading any page on the website, taking about 10 seconds. It appears as though the page ...

Preventing event propagation in AngularJS after sending an AJAX request

When making an ajax request to a server-side script for captcha validation, I want the requested script to prevent default behavior based on the response from the server. Here is the code snippet: $scope.submit = function(e){ s_registration.captc ...

What is the best way to retrieve user input from a form within an Ajax.ActionLink?

My webpage is designed to be simple, featuring a picture and a comment section that functions as a partial view. I am looking to only refresh the partial view when a new comment is submitted. Here's what I have coded: <tr> & ...

Stop music with one click, code in Javascript

I am encountering an issue with a set of 5 div boxes on my website. Each box is supposed to play a specific audio track when clicked, based on data attributes. However, I'm having trouble pausing the previous track when clicking on a new box, resultin ...

What is the best way to combine two JSON objects within the same array based on their IDs located in another array?

I am dealing with a large JSON array that contains multiple objects and arrays. I need to combine two types of objects together. For example, numbers 1-10 represent "Froms" and numbers 11-20 represent "Tos". I want to merge Froms and Tos, displaying them ...

adjusting array based on screen size fluctuations

Imagine having two arrays of images named landscape_images[] and portrait_images[]. One is for the landscape view and the other for the portrait view. When the screen width is in landscape mode, the wide resolution images will be displayed on the body. C ...

The getBBox() method of SVG:g is returning an incorrect width value

Hey there, I've been attempting to determine the width of a <g> element and it consistently returns 509.5 pixels regardless of what I do. Initially, I assumed this was the actual size and not scaled. However, upon opening the SVG in Illustrato ...

Understanding special characters within a URL

Here is a URL example: postgres://someuser:pas#%w#@rd-some-db.cgosdsd8op.us-east-1.rds.amazonaws.com:5432 This URL is being parsed using the following code snippet: const url = require('url'); const { hostname: host, port, auth, path } = url.par ...

Socket.io continuously refreshing and updating multiple instances

Incorporating socket.io into a small React application, I configured all the listeners within the "componentWillMount" method. See the code snippet below for reference: componentWillMount() { const socket = io(); socket.on('update', f ...

When the state inspection fails due to a missing object property, the function will not work as intended

I'm currently in the process of developing a weather app. The user will input either a zip code or a city name + state, triggering the $.getJSON function to gather data. One key feature I am working on involves checking if the user's input is va ...

Using PHP to read an image blob file from an SVG

Currently, I am utilizing the Raphael JS library on the client-side to generate a chart in SVG format. However, my goal is to make this chart downloadable, which poses a challenge since SVG does not natively support this feature. Initially, I attempted to ...

Leveraging ajax data to enhance visual representation in graphs

Having trouble fetching data from a database to display it in a graph.js graph. I've attempted setting a timeout for the async callback from Ajax, but nothing seems to be working. Any suggestions on how to make this work would be greatly appreciated! ...

Verify if item is currently on wishlist

Is there a way to verify if products have been added to the wishlist for logged in customers? I would like to display the result on a twig file, showing whether the product is already on the wishlist. button color=red else button color=gray In addition, ...

Aligning the canvas resolution to match the video resolution for superimposition purposes

Within a div, I have both a canvas and a video element: <div id="videos"> <canvas id="my-canvas"></canvas> <video id="remote-video" autoplay></video> </div> Below is the css styling for both elements: #my-canv ...

"Enhance Your Design with Hovering CSS Backgrounds

Seeking assistance with changing the background image on span hover. If anyone can assist, I have included the complete code for the website below. Take a look at the full website code here: Pastebin CSS Pastebin JavaScript ...

HTML experiences confusion as JSON tosses undefined data

Can someone assist me with API integration? I am new to this and trying to display the Poster, Title, and Year from an API URL. Here is the code I have been working on. When I log in, it shows JSON in an array but throws "undefined" in front-end. Your help ...

Having difficulty updating an angular variable within a callback function

Currently, I am utilizing the Google Maps directions service to determine the estimated travel time. this.mapsAPILoader.load().then(() => { const p1 = new google.maps.LatLng(50.926217, 5.342043); const p2 = new google.maps.LatLng(50.940525, 5.35362 ...

Check for support of Symbol.toStringTag in JavaScript

Can this function reliably detect the presence of @@toStringTag in all environments? function hasToStringTagSymbol() { if (Symbol && (typeof Symbol() == "symbol") && !!Symbol.toStringTag) { var xTest = function () { }; xTest.prototyp ...