How to load Localstorage values ​​in dynamically loaded dependent drop-down lists?

I'm sure there is an answer, but I'm completely confused and don't know who to turn to. I can't find any answer that works on the web. I have multiple selection groups / dropdown options dependent (three per group) which are loaded via ajax from a server. The first drop-down list in each group works. But the second and third do not. I have TWO (2) problems. The first problem is that I cannot retrieve the values ​​in localstorage to reload them in the perspective drop-down list after refreshing the page. The second problem is that the value stored in localstorage is not the correct value that was actually selected from the drop-down list. It appears that local storage stores the last value in the drop-down list or the first value in the drop-down list. Local storage in the second drop-down list always stores the last value and the third drop-down list always stores the first value.
local storage values ​​are present but will not be loaded in the drop-down menu

I would appreciate any help you could give me on this problem and on writing code in general. The call jquery and ajax is as follows;

    $(document).ready(function () {
$('.country').on('change', function () {
    var countryId = $(this).val();            
    var state_select = $(this).closest('form').find('.state');
    var city_select = $(this).closest('form').find('.city');            

    if (countryId) {
        $.ajax({
            type: 'POST',
            dataType: 'json', 
            url: 'ajaxData.php',
            data: {
                country_id: countryId
            },
            success: function (r) {
                console.log('States', r);                        

                if (r.status) {
                    r.data.forEach(function (state) {
                        $(state_select).append(``);                  

                        $('.state').each(function(r) {
                            var stateList = $(state);
                            var thisSelection = $(this);
                            var thisId = thisSelection.attr('id');
                            var storageId = 'state-' + thisId;
                            var storedInfo = localStorage.getItem(storageId);



                            thisSelection.on('change', function(e) {                                    
                                var selectedOptions = ();
                                thisSelection.find(':selected').each(function(i) {
                                    var thisOption = $(this);
                                    selectedOptions.push(thisOption.val());
                                });
                                localStorage.setItem(storageId, (state.name));

                            });
                        });                                
                    });

                } else {                            
                    $(state_select).html('');
                    $(city_select).html('');
                }

            }
        })
    };
}); 
$('.state').on('change', function () {
    var stateId = $(this).val();            
    var city_select = $(this).closest('form').find('.city');

    if (stateId) {
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: 'ajaxData.php',
            data: {
                state_id: stateId
            },
            success: function (r) {
                console.log('Cities', r);

                if (r.status) {
                    r.data.forEach(function (city) {
                        $(city_select).append(``);                    

                        $('.city').each(function(i) {
                            var stateList = $(city);
                            var thisSelection = $(this);
                            var thisId = thisSelection.attr('id');
                            var storageId = 'city-' + thisId;
                            var storedInfo = localStorage.getItem(storageId);


                            thisSelection.on('change', function(e) {                                    
                                var selectedOptions = ();
                                thisSelection.find(':selected').each(function(i) {
                                    var thisOption = $(this);
                                    selectedOptions.push(thisOption.val());
                                });
                                localStorage.setItem(storageId, (city.name));
                            });
                        });                                
                    });
                } else {                            
                    $(city_select).html('');
                }
            }
        })
    };                       
});   
});          

The HTML markup is as follows;

 

Please help. THX

How to return localStorage values ​​from javascript to PHP?

I'm trying to use localStorage to store values ​​and retrieve them in PHP, in Drupal 7. I configure the vars by building a localStorage.setItem call string and using drupal_add_js, which works, but I do not know how to bring them back to my PHP. Is it possible to call a js file and return its return value to PHP? The only examples I've found involve having the form fields set, but this application does not use a form.

typescript – How to clear LocalStorage before initializing Angular 7App

I am building a JWT connection application using Angular 7. I have created a service – AccountService, to manage the login / logout feature, and it works as expected. but my problem is this: local storage is erased only when an event is triggered from the application. and thus the tokens and connection variables are erased. If a user closes the browser without logging out and enters the home URL in the address bar, he or she goes to the home page and uses the previous tokens.

How can I make sure that when a user closes the browser or runs the application for the first time, the system completely clears the local storage and prevents access to the road from the home page, thus redirecting you to the connection route.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, Subject, BehaviorSubject } from 'rxjs';
import { map } from 'rxjs/operators';

import { Router } from '@angular/router';


@Injectable({ 
  providedIn: 'root' application..
})


export class AccountService {

  private baseUrlLogin:string = "/api/account/login";

  private loginStatus = new BehaviorSubject(this.checkLoginStatus());    //subject/observable/BehaviorSubject  
  private userName = new BehaviorSubject(localStorage.getItem('userName'));
  private userRole = new BehaviorSubject(localStorage.getItem('userrole'));

  constructor(
    private http:HttpClient, 
    private router: Router
  ){}

  login(username:string, password:string){

    return this.http.post(this.baseUrlLogin,{username, password}).pipe(
               map(result => {
                  if(result && result.token){
                      localStorage.setItem('loginStatus', '1'); 
                      localStorage.setItem('jwt', result.token);
                      localStorage.setItem('userName', result.username),
                      localStorage.setItem('expiration', result.expiration),
                      localStorage.setItem('userRole', result.userRole);

                      this.loginStatus.next(true); 
                      this.userName.next(localStorage.getItem('userName'));
                      this.userRole.next(localStorage.getItem('userRole'));
                  }
                  return result;

               })
           );

  }

  logout(){
    this.loginStatus.next(false);
    this.clrLocalStorage();
    this.router.navigate(('/login'));
  }


  clrLocalStorage(){
    localStorage.setItem('loginStatus', '0');. 
    localStorage.removeItem('jwt');
    localStorage.removeItem('userName'),
    localStorage.removeItem('expiration'),
    localStorage.removeItem('userRole');
    localStorage.clear();
  }

  checkLoginStatus():boolean{
    var loginCookie = localStorage.getItem("loginStatus");         
    if(loginCookie == "1"){ 
      return true;
    }
    this.clrLocalStorage();
    return false;    
  }   

  get isLoggedIn(){
    return this.loginStatus.asObservable(); 
  }

  get currentUserName(){
    return this.userName.asObservable(); 
  }

  get currentUserRole(){
    return this.userRole.asObservable(); 
  }    

}

on my home controller, on the ngInit method – life cycle, that's what I

 ngOnInit() {
    let isLoggedIn = this.acc.checkLoginStatus();
    if(!isLoggedIn){
      this.router.navigate(('/login'));
    }else{
      console.log('welcome home... ');
      console.log(localStorage);
    }

  }

if i restart the server, i also want to completely clear the cache, and after the launch, it should redirect to the homepage, please, what is the right way to there take.

html – JavaScript `localStorage` with the alternative` document.cookie` for static websites

The code

Until now, things have worked as desired and I hope that new eyes will be able to report any error or item that can be improved, a live demo is hosted and updated on GitHub Pages , and the source code is only one file. fork or clone a way….

BrowserStorage.js

BrowserStorage class {
/ **
* @this BrowserStorage
* /
constructor () {
this.supports_local_storage = this.supportsLocalStorage ();
this.supports_cookies = this.supportsCookies ();
this.storage_available = (this.supports_cookies || this.supports_local_storage)? right wrong;
}

/ **
* Note, use `this.supports_local_storage` instead in the tests.
* @returns {boolean}
* /
supportsLocalStorage () {
try {
let key = & # 39; test & # 39;
let value = true;
localStorage.setItem (key, value);
localStorage.getItem (key);
localStorage.removeItem (key);
} catch (e) {
returns false;
}
return true;
}

/ **
* Note, use `this.supports_cookies` instead in the tests.
* @returns {boolean}
* /
supportsCookies () {
if (navigator.cookieEnabled) returns true;

try {
document.cookie = & # 39; testcookie & # 39 ;;
} catch (e) {
returns false;
} finally {
if (document.cookie.indexOf (& # 39; testcookie & # 39;)! = -1) {
this.remove (& # 39; testcookie & # 39;);
return true;
}
returns false;
}
}

/ **
* Copy of the `constructor` method which should not come from a type error
* /
constructorRefresh () {
this.supports_local_storage = this.supportsLocalStorage ();
this.supports_cookies = this.supportsCookies ();
this.storage_available = (this.supports_cookies || this.supports_local_storage)? right wrong;
}

/ **
* Gets the specified value of browser storage and URI components when returning
* @returns {? boolean |? number |? string}
* @this BrowserStorage
* /
Get the key) {
let value = null;
if (this.supports_local_storage) {
value = localStorage.getItem (key);
} else if (this.supports_cookies) {
leave cookie_data = document.cookie.match (& # 39; (^ |;)? + key + & # 39; = ([^;]*) (; | $) & # 39;)
value = cookie_data? cookie_data[2] : no;
}
returns encodeURIComponent (value);
}

/ **
* Removes the value selected by key from the browser storage; note for cookies, _full whipe_ will be displayed when loading the next page
* @returns {boolean}
* @this BrowserStorage
* /
remove (key) {
if (this.supports_local_storage) {
localStorage.removeItem (key)
return true;
} else if (this.supports_cookies) {
// Note, how to disable and expire in the past
// to delete a cookie the next time the page loads.
this.set (key, -7);
return true;
}
returns false;
}

/ **
* Stores the client settings in the browser, _serverless_ in the real sense
* key @peram {string | number} - _name variable_to store the value under
* value @peram {boolean | number | string} - stored under localStorage or as a cookie
* @peram {number} days_to_live - how long is a browser suggested to keep cookies
* @returns {boolean}
* @this BrowserStorage
* /
set (key, value, days_to_live = false) {
if (this.supports_local_storage) {
localStorage.setItem (key, value);
return true;
} else if (this.supports_cookies) {
let expire = & # 39 ;;

if (days_to_live) {
let date = new Date ();
if (days_to_live == 0) {
date.setTime (date.getTime ());
} other {
date.setTime (date.getTime () + (days_to_live * 24 * 60 * 60 * 1000));
}
expires = & # 39 ;; expires = + date.toGMTString ();
}

document.cookie = name + & # 39; = & # 39; + value + expires + & # 39 ;; path = / & # 39 ;;
return true;
}
returns false;
}

/ **
* Clear ** all ** LocalStorage client or cookie settings
* @returns {boolean}
* @this BrowserStorage
* /
clear () {
if (this.supports_local_storage) {
localStorage.clear ();
return true;
} else if (this.supports_cookies) {
leave the cookies = document.cookie.split (& # 39 ;;);
for (ie i = 0; i <cookies.length; i ++) {
leave cookie = cookies[i];
let key = encodeURIComponent (cookie.split (& # 39; = & # 39;)[0].replace (/ (^  s + |  s + $) / g, & # 39;));
if (typeof (key) == <string> || typeof (key) == # number;) {
this.remove (key);
} other {
returns false;
}
}
return true;
}
returns false;
}

}

main.css

/ **
* 1. Central element
* 2. Re-justify the text
* /
body {
text-align: center; / * 1 * /
}

.container__main_content {
maximum width: 80%;
maximum width: 80vw;
display: inline-block; / * 1 * /
text-align: left; / * 2 * /
}

/ **
* Note on confidentiality
* /
.container__privacy_notice {
position: fixed;
bottom: 5px;
maximum width: 80%;
maximum width: 80vw;
background color: light gray;
text-align: left; / * 2 * /
}

.privacy_notice__label {
background color: black;
White color;
font size: 1.5rem;
upholstery: 5px 10px;
Float on the right;
}

.privacy_notice__label: hover {
color: light gray;
}

/ * Status of the label when the check box is unchecked * /
.privacy_notice__label :: after {
content: attr (value);
}


/ **
* Tweaks
* /
.hidden__input {
display: none;
visibility: hidden;
opacity: 0;
filter: alpha (opacity = 0);
}


/ * Status updates when the check box is checked * /
.privacy_notice__checkbox: verified ~ .container__privacy_notice {
box-shadow: not defined;
max-width: 1.5rem;
maximum height: 1.5rem;
}

.privacy_notice__checkbox: checked ~ .container__privacy_notice * {
visibility: hidden;
opacity: 0;
filter: alpha (opacity = 0);
}

.privacy_notice__checkbox: verified ~ .container__privacy_notice .privacy_notice__label :: after {
content: attr (verified);
}

/ * Status of the label when the checkbox is checked * /
.privacy_notice__checkbox: verified ~ .container__privacy_notice :: after {
content: & # 39;  1F56D & # 39;
position: absolute;
bottom: 5px;
left: 5px;
}

/ * List of verified and hovering updates * /
.privacy_notice__checkbox: verified ~ .container__privacy_notice: hover {
maximum width: 80%;
maximum width: 80vw;
maximum height: not defined;
}

.privacy_notice__checkbox: checked ~ .container__privacy_notice: hover * {
visibility: visible;
opacity: 1;
filter: alpha (opacity = 100);
}

index.html



  
    Example of BrowserStorage
    
    

    
    

    
  

  
    

It is a static site that gives the illusion of remembering a customer. Test by accepting privacy notice then refreshing or close and reopen a tab pointing to the current URL.

Ctrl R or Ctrl shift R will refresh most desktop browsers.

Then reject the privacy statement by clicking the Acceptable button again to reverse the behavior of this site.

use Ctrl shift I open the debugger on a desktop browser, and then go to the tab / pane Storage to observe JavaScript does things for the actions mentioned above.

This site uses JavaScript, and local storage or cookies from your browser, to improve your experience here, however, this site is currently doing do not store data about your server-side activity.

Review the Privacy and security notice concerning the BrowserStorage.js , for more details on using storage and client-side scripts.

Note, I have tried using the Web Code option when writing this question, but this has caused various errors.

Questions

My goal is to have 100% coverage for browsers using JavaScript and local storage or document.cookie storage options;

  • in this day n age is it useful to use cookies for local backup storage?

  • is it useful to use the old syntax to get the OO behavior of JavaScript or use the class and a function keywords are enough?

if there are good arguments for not using class, please include feature detection examples to load another version.

  • I keep running through nper but it seems to be more focused on node-related JavaScript, should I consider issuing npm init. or would it be pollute their parcel management system?

If such projects are a good candidate for nper, then some tips on agnostic publishing methods of the operating systems Git the orders would be excellent.

  • I am currently using encodeURIComponent when returning values ​​stored in the browser, however, this leads to unpredictable behavior with Boolean and numeric values ​​(sometimes a string, sometimes not), better way to recover values?

At this point, it seems almost necessary to do a pre-check before returning to get some consistency in behavior.

  • Where did I go wrong and / or how can I improve code execution without sacrificing readability?

  • One thing I find annoying to use checkbox hacks is accessibility, are there any well ways to get Tongue and Space/Enter support?


Thank you, and I hope that even though the above is me being a bad influence that we can all learn why together.

How to receive LOCALSTORAGE data sent by AJAX on my PHP server?

That's my first question, I'm waiting for your help.

I have this code on my server to receive the data that comes from my ajax that I pull from a Localstorage storage, for this example there is only one variable that I would like to write not only in the document your_data.txt which makes file_put_contents but in the moment of retrieving the information, PHP manages them and stores them in MYsQL bd or send them to me by e-mail, help us, please 🙁

<? php
date_default_timezone_set (America / Chicago & # 39;) // CDT
echo

Server time zone: & # 39 ;. date_default_timezone_get (). & # 39;

& # 39 ;; $ current_date = date (d / m / Y == H: i: s); to print "

Server time: ". $ Current_date."

"; $ dataObject = $ _POST['data']; $ json = json_decode ($ dataObject, true); file_put_contents (& # 39; your_data.txt) & # 39 ;, $ json);

?>













enter the code here













my server receives with this PHP, it saves me only in a txt.

javascript – prevents time reset with LOCALSTORAGE

Hello.
I have a code that when you click on the button, it starts a countdown of 5 seconds, and it displays a message on the same button, that's all.
But I would like that when the page is updated, it will not restart, but that I continue counting until it reaches zero. I understand that it is possible with the local storage, I try but I still do not get anything, and I would like that one can help me with that. and if it is possible that the time passing is indicated on the same button, but if you can with local eStorage, I am very grateful to you.
Thank you for your time, my friends.

openButton male;

initial function () {
document.getElementById ("initial"). innerHTML = ".................";

openButton = setTimeout (function () {
document.getElementById ("initial"). innerHTML = "CLICK";
}, 5000, "JavaScript");
}
    

Web Application – Is LocalStorage in Web Browsers Safe enough to Store Passwords?

I am building a system where users can enter an email address and password on my login page. If they then click the registration button, they store this data in LocalStorage before redirecting the user to the registration page.

The registration page then checks LocalStorage and automatically fills in the e-mail address and password of the previous page.

My question is: how does LocalStorage store this type of data? Storing RAW passwords in this way seems like a bad idea. That being said, everything is local on the device of the user. It is not sent to any server or anything, which reduces the risk of attack.

I've also considered deleting the LocalStorage element after getting it back on the registration page. Which would make it safer.

How secure is LocalStorage for storing RAW passwords and this type of data?

localStorage – How to store the data of multiple users? [pendente]

I am working on a front project and I need to register multiple users and their correct addresses on the local storage to display them on my main page. How can I do this using only HTML, CSS and JavaScript?

xss – What is the security risk of storing an authentication token in localStorage versus cookies?

A cookie marked httpOnly, as its name indicates, is not accessible from javascript. Thus, a "conventional" web application using cookies is not vulnerable to naive XSS attacks if this flag is set (assuming no browser bug exposes it naturally). In particular, such a solution is vulnerable to CSRF; an extra effort is needed to remedy this.

In SPA frameworks, you usually need to have access to the javascript cookie because they want to put it in an authorization header and not just rely on old school-based cookie-based security. This has the advantage of being now resistant to the CSRF.

The basic reason for a SPA is that if someone manages to inject javascript, he won. You must not have XSS vulnerabilities because the attacker can change everything about your application and simply make any malicious action with the stolen token in the victim's browser. (or simply modify your application to steal the password in plain text of the user …)

As a result, people choose to tolerate the potential exposure of the session token because the supposed consequence of a successful XSS on a SPA is anyway a 100% compromise.

(In my opinion this is not at all a regulated subject, people still have heated arguments about it. There is an incalculable number of blog posts and flame wars on the forums that fight on both sides

angle – Ionic 3 LocalStorage disappears

I have an application in Ionic 1 that records information about local storage.
I have rewritten the same application on Ionic 3 with the same package ID (widget ID in config.xml), but when installing the new application on the old, I lose the localStorage, this one is empty.

If I install the old version again over the new one, I can see localStorage again, it's as if they were different applications, but they have the same package ID and j & # 39; 39, always installs on each other.

This only happens on mobile, applications do not share the same local storage. When accessing Google Devtools in the "Application" tab – "Storage" – "Local Storage", "file: //" appears when I drag the application created in Ionic 1 and "http: // localhost: 8080". created in Ionic 3.

Is there any particularity in Ionic 3 that can not see / access Ionic 1's local storage and vice versa?