Search code examples
javascriptphpsettingslocalstore

php js - Store user settings on his computer


I would like to create a tiny script for web visitors :

A single sentence saying "Welcome {your name}." By cliking on {your name} the user would be able to write ... his name. I can do that by myself.

My question is : What is the best way for the user to see his name the next time he comes back ?

How to store this data in local user storage ?

Thanks for your advice !


Solution

  • If you want to store the name in the local storage of the user web browser you can use localStorage (just simple JavaScript). Something like this:

    html

    <input id='name'>
    <a onclick="saveName()">Save</a>
    <a onclick="showName()">Show Name</a>
    

    js

    function saveName() {
      var name = document.getElementById('name').value;
    
      if (typeof(Storage) !== "undefined" && name) {
        localStorage.setItem('userName', name);
      } else {
        alert('Sorry! No Web Storage support..');
      }
    }
    
    function showName() {
      if (typeof(Storage) !== "undefined") {
        alert(localStorage.getItem('userName'));
      } else {
        alert('Sorry! No Web Storage support..');
      }
    }
    

    If you want the user to be able to access his/her info independently of the browser you should consider storing it in the database.