javascriptjquerylocal-storageweb-storage

Using localstorage inside Jquery done method


I want to set a localstorage inside .done method when user's answer is correct. Then i want to get that local storage object and use that outside of the done method. How is that possible? Below is what i am trying without success.

data.color is a string

$.ajax({
    type: "POST",
    url: "validation.php",
    dataType: "json",
    data: $("input").serialize(),
}).done(function(data) {
 if (data.answer) { //if answer is correct
 localStorage.setItem("ColorStorage", data.color); //set a local storage with the variable data.color
    }
});

//outside of ajax
if (localStorage.getItem("ColorStorage") > 1)
    $("#result").append(localStorage.getItem("ColorStorage"));

Solution

  • The returned value from localStorage.getItem("ColorStorage") is a String, so compare it with e.g. a number like > 1 won't work.

    You can e.g. omit the > 1 and it will return true if the item exist.

    if (localStorage.getItem("ColorStorage"))  {
    
    }
    

    You can of course also check its length, though after you made sure it exists, or else you will get an error if it doesn't.

    if (localStorage.getItem("ColorStorage") && localStorage.getItem("ColorStorage").length > 1)  {
    
    }
    

    Also do note, if you make that call before the AJAX call is done, the item won't exist, though with the above code sample it won't result in a runtime error.