Is there a way to retrieve data from local storage after every login in Laravel?

Utilizing Laravel 5.3, I have been storing my data on local storage using JavaScript:

localStorage.setItem('storedData', JSON.stringify(data))

Now, when a user logs in, I want to implement a condition. If the stored data exists in the local storage, I would like to retrieve it and save it in the database.

Is there a straightforward way to achieve this, possibly through the use of Ajax?

Answer №1

When it comes to accessing local storage, it can only be done on the client side using JavaScript. If you need to fetch data on the server side, consider using session or cookies (if the data size is less than 4kb).

If you still prefer to use local storage, you will need to write an AJAX call to send the data to the server.

$( document ).ready(function() {
   var myData = localStorage.getItem('storedData');
   if(myData == undefined || myData == ""){
    } 
   else{
      $.ajax({url: "dostuff.php",
         data:{data:myData },
         success: function(result){
             localStorage.clear();
        }});
    }
  });

Answer №2

$( document ).on('load', function() {
    var dataCheck = storage.getItem('storedData');
    if (dataCheck) { 
        $.ajax({url: "performaction.php", success: function(response){
            //DO ACTION
        }});
    }
});

Answer №3

  1. Store the value in localStorage when logging in.
  2. Include a common js file in the header for all pages post-login.
  3. In this script,

    $( document ).ready(function() {
     var myData = localStorage.getItem('storedData');
     if(myData == undefined || myData == ""){
      window.location = "/logout";
     } 
     else{
     //Perform ajax request and send data to controller
     }
     });
    
  4. Clear localStorage data when loading the login page.

    localStorage.clear();
    

Suggestion:

It might be more secure to use session storage for these types of tasks.

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

Failure Caused by Changing Value in Radio Button

I have been struggling with a particular issue for some time now, and I am hoping someone can provide an answer. The task at hand is quite simple - I am attempting to create an input within an *ngFor loop. However, the radio buttons are not functioning as ...

Utilizing Map Function within Nested Ternary Expressions in React

Can anyone help me with restructuring the nested ternary operator in this code snippet? I am getting an error that says "Unexpected token, expected ","" and I'm not sure how to fix it. Essentially, if edit is false, I want to render the first li. If t ...

Manipulating Strings in JavaScript Arrays

I am working with an array of arrays of data that is being retrieved from a csv file. My goal is to filter out specific indexes of an array based on the titles they contain. For instance: If an array index includes the title "Retail", I want to return the ...

Unit Testing JWT in Angular 2

Using JWT for authentication in my API calls. I am in the process of coding a service method. An interceptor is applied to all requests: public interceptBefore(request: InterceptedRequest): InterceptedRequest { // Modify or obtain information from ...

Streaming data from MongoDB to a file using Node.js

Having recently delved into the world of javascript/node.js, I am attempting to accomplish a basic task: connect to MongoDB, convert the JSON response to CSV format, and then write it to a file. My current approach is outlined below: fs = require('fs ...

Can someone provide guidance on effectively implementing this JavaScript (TypeScript) Tree Recursion function?

I'm currently grappling with coding a recursive function, specifically one that involves "Tree Recursion". I could really use some guidance to steer me in the right direction. To better explain my dilemma, let's consider a basic example showcasi ...

Encountering a "404 not found" error when trying to access `/en/first` with the routing

I am currently working on setting up a routing module in Node.js & express, but I seem to be encountering some issues. The specific error message I am getting is Cannot GET /en/first The goal is to organize different folders like 'en', each wit ...

Using Javascript Regex to conceal non-ASCII characters in strings

I'm currently working on masking strings using JavaScript regex. However, I've encountered an issue with non-ascii characters. How would you suggest resolving this problem? Below is the code I've been using: var name = "Üsüaüü Bxbd ...

Issue with event listener arising once elements have been loaded into the dom

I have a project where I want to click on a category card to obtain its id and then redirect to the movies screen. I understand that using row.eventlistener() in index.js executes before the elements are rendered, causing the id not to be captured. How ca ...

What is the method to set up the "materializecss" modal with the "before" (beforeload) feature?

Trying to implement the modal functionality in my project using the materializecss framework but facing some challenges. I have created a popup modal for an image with the code below: HTML: <div class="media-insert"> <a href="#img2" class="moda ...

Is it possible to create a unique AJAX function for a button element within a table?

Using an ajax function, I am populating a table with data from a PHP file that returns JSON encoded data. Each row in the table includes data as well as three buttons for delete, edit, and save operations specific to that row. The issue arises when I atte ...

Refresh the angular scope when events are triggered

I am integrating a web service client into an angular service. This specific client sends out events for certain updates like this: app.service('AngularClient', function () { this.info = null this.login = function () { client.login(login ...

Trigger a popup using the javascript .link() method

I am currently using ag-grid to present JSON data. When the values are located within nested objects, I have to utilize a valueGetter from the grid API to map to the appropriate value. The value getter returns a value for each row and the grid matches it t ...

"Although Highcharts' parsed drilldown is not displaying on the page, it is visible in the

I successfully created a column chart using Highcharts 4 with jQuery 1.9.1 by parsing a CSV file. The page loads with the chart displayed, but when I click on a bar, nothing happens. Upon checking the console in IE11, I can see that the arrays are being ge ...

Is it possible to use the Three.js LoadingManager to load videos?

I am currently using THREE.LoadingManager in conjunction with various loaders to efficiently handle the loading of textures, models, images, and cubeTextures before my app is displayed. This setup enables me to present a loading bar that shows the overall ...

Navigating and Controlling the DOM in Angular 4

Can anyone help me figure out how to reach a DOM element in Angular 4? I'm really struggling with this concept and I've been trying to understand ElementRef, ViewChild, and other methods, but I just can't seem to grasp how to navigate throu ...

Navigating JSON/API data within a Vue.js component template: step-by-step guide

I've successfully implemented a code snippet that renders a list of songs here: https://jsfiddle.net/jeremypbeasley/guraav4r/8/ var apiURL = "https://ws.audioscrobbler.com/2.0/?method=user.gettoptracks&user=thisisheroic&period=7day&limit= ...

What is the best way to change an existing boolean value in Prisma using MongoDB?

Exploring prisma with mongoDb for the first time and faced a challenge. I need to update a boolean value in a collection but struggling to find the right query to switch it between true and false... :( const updateUser = await prisma.user.update({ where: ...

Even though I've already assigned a key prop in React, I am still receiving a warning message about the

In the following code snippet, I am creating a note card element with a specific key. However, whenever I attempt to edit my note element, I encounter a warning that states: Warning: Each child in a list should have a unique "key" prop. Here is a portion ...

Conflicting submissions

Can anyone help me with a JavaScript issue I'm facing? On a "submit" event, my code triggers an AJAX call that runs a Python script. The problem is, if one submit event is already in progress and someone else clicks the submit button, I need the AJAX ...