-2

I have a index.php and index.js file imported in the first file. From the index.js i call a function from index.php that sets localStorage.some_item with some string. In the same file index.js, right after I called the function which sets in local storage, I am trying to get from the same index of localStorage.some_item, but I get undefined!

It is because, writing to local storage takes some time and can't read it right away? I tried delaying, reading it, but got the same result. Maybe for some reason the scripts are run asynchronous, even if they shouldn't...What could be the issue here? I could try different approaches to fix it, but I want to understand what is happening.

Did anyone encountered this behaviour or could help? Thank you

In index.js:

setDataInLS();
var sSomeData = localStorage.getItem('some_data');
console.log("localStorage.some_data = ",sSomeData);

In index.php:

function setDataInLS(){
        $.getJSON("getSomeData.php",function(jData){
            console.log(jData);
            var sData = JSON.stringify(jData);
            localStorage.setItem('some_data', sData);
        });
    }
Dan Romulus
  • 95
  • 2
  • 13

1 Answers1

0

With @Bergi's help I managed to find a solution. Waited for the $.getJSON and setting to local storage to finish until I read the data from local storage. Thank you very much!

For the down-voters, sometimes because of tiredness you can't see what's obvious...

Dan Romulus
  • 95
  • 2
  • 13