How to set data in the localStorage

1

I have the following code:

$scope.loginUser = function (user) {
    console.log(user);
    $http.post("admin/php/login.php", user).then(function(response){

    if(typeof(Storage) !== "undefined") {
            localStorage.setItem("chave", "valor - algum conteudo aqui");
            var valor = localStorage.getItem("chave");
            console.log(valor);
        } else {
            console.log("Desculpe, mas o navegador nao possui suporte a Web Storage.");
        }
        $window.localStorage.setItem("idUsuarios",idUsuarios);
        $window.localStorage.setItem("nome",nome);
        $window.localStorage.setItem("email",email);

        //console.log(response);
        $location.path('admin/views/painel');

    })
}

How do I set the data for who is stored in localStorage ?

$window.localStorage.setItem("idUsuarios",?);

PHP:

<?php
$data = json_decode(file_get_contents("php://input"));
$email = $data->email;
$senha = $data->senha;

$sql = mysqli_query($con, "SELECT * FROM usuarios WHERE email='$email' AND senha='$senha' ");

$return = array();

while($row = mysqli_fetch_array($sql,MYSQLI_ASSOC)){
      $return = $row;
}

echo json_encode($return);
    
asked by anonymous 06.01.2016 / 22:41

2 answers

1

localStorage writes only texts, so it is necessary to have the information in text format that can be obtained with JSON.stringify if necessary.

var test = ["Hello", "World", "Item 3", 5];

if (typeof(Storage) !== "undefined") {  

    //Gravando no localStorage
    localStorage.setItem("Teste", JSON.stringify(test));
    //

    //lendo do localStorage
    var itens = JSON.parse(localStorage.getItem("Teste"));
    //

    for (var s of itens) {
      var node = document.createElement("LI");
      node.innerHTML = s;
      document.getElementById("result").appendChild(node);
    };
} else {
    var node = document.createElement("LI");
    node.innerHTML = "'localStorage' Não suportado";
    document.getElementById("result").appendChild(node);
}

Follow the example in JSFiddle

    
06.01.2016 / 23:19
0

First, add a condition to check if the browser has support, then use setItem () to insert an item into the localStorage, this function accepts two parameters, which are key and value.

Example:

var id = 1;
var nome = "Gabriel";
var email = "[email protected]";
if (typeof(Storage) !== "undefined") {
  localStorage.setItem("id", id);
  localStorage.setItem("nome", nome);
  localStorage.setItem("email", email);
  print("id");
  print("nome");
  print("email");
} else {
  console.log("Desculpe, mas o navegador nao possui suporte a Web Storage.");
}

function print(key) {
  document.getElementById("result").innerHTML += localStorage.getItem(key) + "<br>";
}
<div id="result"></div>

See working at jsfiddle

    
06.01.2016 / 22:49