0

I am wondering if I can call variables outside the getJSON, having a multilingual website, json file looks like (lang_fr.json, lang_en.json):

{
    "HOME": "Home",
    "ABOUT": "About",
    "CONTACT": "Contact us",
    "EMAIL": "E-mail Id",
    "CHOOSE_FILE": "Please choose at least one file",
    ETC
}

I all the getJSON, and would like to store variables, to use them later on the page, it can be error messages to display, or a menu,..

$(document).on('click', '#upload', function () {

// some code goes here

    $.getJSON('cdns/json/lang_' + memLang + '.json', function (dlang) {
      console.log(dlang);

      var  storeKeys  = [];
      var  storeVals  = [];
      $.each(dlang, function(x, y){
        storeKeys.push(x);
        storeVals.push(y);
      });
    });

    console.log(storeKeys); // empty
    console.log(storeVals); // empty

Then try to get these variables to use down:

/*** Some code goes here */

let choosefile = storeKeys.CHOOSE_FILE;

if (!fileValue) {
            $('#loadingResult').html(choosefile);


//End code
newCoder
  • 25
  • 3
  • @CBroe - FWIW, there's also the more specific https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron – T.J. Crowder Sep 29 '21 at 11:11
  • `$.getJSON` is asynchronous because of this the `storeKeys` and `storeVals` arrays are not populated when the code is executed. You can move the `console.log` below the `$.each` and you will get the expected result – MaartenDev Sep 29 '21 at 11:35
  • Thanks for your replies, I used ajax to get my data from json file – newCoder Sep 29 '21 at 13:03

0 Answers0