I have two JS files and in the first one I am initializing a session storage using ajax, so I want use this session storage value in my another JS files. but the problem is that the session storage in another files doesn’t get any value while I have set it in the first initializing JS file earlier.
my sample code is given as bellow:
JS file 1 (initializing JS file that has to be run at first):
$.post(
"mypage.php",
{
},function(data) {
sessionStorage.setItem("data_kind", data.kind);
}, 'json'
);
js file 2 and others (is going to use data_kind which have been initialized in JS file 1):
var my_data_kind = sessionStorage.getItem("data_kind");
console.log(my_data_kind); // it returns null and dont get any value!!!
2
Answers
You have to make sure your
sessionStorage.setItem("data_kind", data.kind)
is already executed at first and make sure you have the right or import js file orderFor me, when I debug my code I usually write console.log(‘execute blabla’, data) to give myself confidence that my code in that line is running and loaded in the right order. Also, don’t forget to delete the console.log when the feature is finished
And, closing a tab/window clear objects in sessionStorage as documented here https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
You’ll only be able to read the value from storage after the AJAX request completes.
$.post()
returns a deferred / promise-like object. Use that to chain something to run after the request completes.For example, assuming your two JS files are included in this order