$.getJSON want to call synchronously

Thank you for helping me with with this.

The code below has the right functionality, but is suboptimal because I am a newbie to asynch functions.

I want to first check if I have all the data I need in localStorage. If the localStorage data exists, I want to use it. If it doesn’t exist, I want to get the data from the server.

I then want to use this data in some code.

To get my code to work, I started with async function $.getJSON and then checked after success if the previous data existed. This means I am getting server data even if I don’t need it and delaying my display.

I would like

  1. If localStorage json data exists —> assign it to the variable a
  2. If localStorage json data does not exists --> read new data and then assign it to the variable a
  3. Use variable a in a bunch of code

I hope I have been clear.

Stuart

$.getJSON(url, function (a) {  

                    if((window.localStorage.getItem("languageJson") && !langParameter))
                    {
                    languageJsonRaw =  window.localStorage.getItem("languageJson");
                    a = JSON.parse(languageJsonRaw);   
                     }

AND then a bunch of code …

Welcome to the forum!

I have a few questions:

Is there a reason you are using localStorage ?
If there is already a localStorage do you need to get the JSON again?

Do you have a defined outside of this function globally?

This part confuses me as to what you are trying to do.

https://europeanwaterproject.org?lang=FR

https://europeanwaterproject.org?lang=DE

So basically, if the user changes the language or its the first time a visitor arrives at the PWA the localStorage will either not be the right language or will not be present.

And on your question regarding defining a outside of the function. No I have not. I am very new to javascript and am coming back to programming after a 25 year hiatus …

Thanks,

Stuart

Well then welcome back to coding! I’m still a newbie (~year experience) … and honestly never dealt with localStorage before, but here is how I would approach it. I hope this helps and maybe others can give better advice :slight_smile:

let data = window.localStorage.getItem("languageJson") //try to get local storage
let lang = window.localStorage.getItem("language") //get language 

if(!data || lang !== langParameter) { //if there is no DATA or different language
   $.getJSON(url, function (a) {  
      // languageJsonRaw =  window.localStorage.getItem("languageJson"); //??
      languageJsonRaw = JSON.parse(a) //parse data 'a'
      let result = languageJsonRaw[langParameter] //assuming a key in JSON?
      localStorage.setItem('languageJson', result)
      localStorage.setItem('language', langParameter)
   });
};

Something like that? Check for the data and only do an update if needed? Unless it is like a news feed and needs to update more often?

Thank you I very much appreciate your help

Sorry for my limited grasp of synchronous functions. I would really like to have a non-synchronous $.getJSON function :slight_smile:

I would like

  1. If localStorage json data exists —> assign it to the variable a
  2. If localStorage json data does not exists --> read new data and then assign it to the variable a
  3. Use variable a in a bunch of code (added below)

I need use a to populate the page on which the user browses whether or not it comes from localStorage or the server. Under the circumstances when I get the data from the server, I need the code below to wait for the success of $.getJSON.

switch(page) {
        case "/site/plastic.html":
        content= "main.plastic.page";
        break;
        case "/site/bottle.html":
        content= "main.bottle.page";
        break;
        case "/site/tap.html":
        content= "main.tap.page";
        break;
        case "/site/project.html":
        content= "main.project.page";
        break;
        case "/site/fountain.html":
        content= "main.fountain.page";
        break;
        default:
        content= "skip";
            }
    $("#MenuLanguage").html(a['menu.language.label']);
    $("#pageTitle").html(a['pageTitle']);
    $("#plastic").html(a['main.plastic.label']);
    $("#bottle").html(a['main.bottle.label']);
    $("#tap").html(a['main.tap.label']);
    $("#project").html(a['main.project.label']);
    $("#fountain").html(a['main.fountain.label']);
    $("#facebook").html(a['main.facebook.label']);
    $("#appLogoLeft").replaceWith('<span id="appLogoLeft"><img src='+a['main.logo'] + '></img></span>');
    $("#appLogoTop").replaceWith('<span id="appLogoTop"><img src='+a['main.logo'] + '></img></span>');

$.getJSON should be asynchronous, it will trigger the function after it gets the JSON payload.

What about an approach like this? Move all of that code from last post into a function,
then call that function as needed. If a already exists call it. If not, do the AJAX call, wait for the data. Then store the data and call the function.

You can also get a “status” from the getJSON such as ‘success’ , ‘error’, ‘timeout’ if you want to handle errors. https://www.w3schools.com/jquery/ajax_getjson.asp

let a = window.localStorage.getItem("languageJson")
if(a) { runThisFunction(a) } //#1
else { //#2
   $.getJSON(url, function (data) {  //get JSON
       localStorage.setItem('languageJson', data) //store
       a = data
       runThisFunction(a)
   });
}

function runThisFunction(a) {
    switch(page) {
        case "/site/plastic.html":
        content= "main.plastic.page";
        break;
    ...
            }
    $("#MenuLanguage").html(a['menu.language.label']);
    $("#pageTitle").html(a['pageTitle']);
...
}

Hope that helps? Sorry it’s late for me. Good luck with your project! Happy coding!

1 Like

This is a great solution !

Thank you for your help.

1 Like