skip to Main Content

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


  1. 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 order

    For 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

    Login or Signup to reply.
  2. 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

    <script src="the-one-that-does-the-ajax-request.js"></script>
    <script src="the-one-that-reads-from-session-storage.js"></script>
    
    // the-one-that-does-the-ajax-request.js
    
    const myPagePromise = $.post("mypage.php", {}, data => {
      sessionStorage.setItem("data_kind", data.kind);
    }, "json")
    
    // the-one-that-reads-from-session-storage.js
    
    myPagePromise.then(() => {
      var my_data_kind = sessionStorage.getItem("data_kind")
      console.log(my_data_kind)
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search