Search code examples
jquerysessionstorage

sessionStorage doesn't work in jQuery


I'm working with sessionStorage for client-side web application. Into index.html I use jQuery to set sessionStorage variable:

$.ajax({
        type: "POST",
        url: "login.php",
        data: "user="+$("#user_name").val()+"&password="+$("#password").val(),
            success: function(html){
                if(html=='true') {
                    $("#add_err").html("Correct. Loading...")               
                    sessionStorage.setItem('sessionUser',$("#user_name").val());
                    sessionStorage.setItem('sessionPassword',$("#password").val());
                    setTimeout(function(){
                        $(location).attr('href','eval.html');
                    },2000);
                } else {
                    $("#add_err").html("Incorrect");
                }
            },
        });

Ok. It works. In eval.html I launch an alert alert(sessionStorage.getItem('sessionUser')); and show me the user.

When I want disconnect the application I click in a button id=btnLogout:

$("#btnLogout").click(function(){
      sessionStorage.clear();
      window.location.assign('index.html');
});

But sessionStorage doesn't clear nothing. I put another alert in index.html and sessionUser is not deleted.

I don't know I'm doing wrong.

Login button from index.html = login.js:

$(document).ready(function(){
    $("#login").click(function(){
        $.ajax({
            type: "POST",
            url: "login.php",
            data: "username="+$("#user_name").val()+"&password="+$("#password").val(),
            success: function(html){
                if(html=='true') {
                    $("#add_err").html("User correct. Loading application...")              
                    sessionStorage.setItem('sessionUser',$("#user_name").val());
                    sessionStorage.setItem('sessionPassword',$("#password").val());
                    setTimeout(function(){
                        $(location).attr('href','eval.html');
                    },2000);
                } else {
                    $("#add_err").html("Incorrect");
                }
            },
        });
    });
}); 

Logout button from eval.html:

$(document).ready(function(){
    $("#btnLogout").click(function(){
        sessionStorage.removeItem('sessionUser');
        sessionStorage.removeItem('sessionPassword');
        window.location.assign('index.html');
    });
});

Solution

  • try removeItem, i.e.

    sessionStorage.removeItem([key]);
    

    So in your code:

    $("#btnLogout").click(function(){
          sessionStorage.removeItem('sessionUser');
          sessionStorage.removeItem('sessionPassword');
          window.location.assign('index.html');
    });