0

I am unable to assign the return value of a XMLHttpRequest (which searches for a string in a tiny csv file and returns its value in the desired language) to a variable. It always says that the string is undefined.

I have even added a delay to give time to the XMLHttpRequest to read the csv file (which is just a few lines btw) but to no avail.

Any suggestions please! I'm stuck!

function DisplayItemInCorrectLanguage()
{
        var str = GetLocalizedTerm ("CBRAND", Language);
        console.log('str: ', str); //Does not work. Error: 'str:  undefined'
}

function GetLocalizedTerm (itemname, language)
{
    var itn = itemname;
    var lng = language;

    var oReq = new XMLHttpRequest(); 
    oReq.onload = function()
    {
        //console.log("String is: ", this.responseText); //log is correct: 'String is:  CAR BRAND'
        //return this.responseText; //Does not return any value to DisplayItemInCorrectLanguage()
    };
    oReq.open("get", "GetLocalizedTermFromDictionary.php?itemname=" + itn + "&LANG=" + lng, true);
    oReq.send();
}
jeddi
  • 651
  • 1
  • 12
  • 21

1 Answers1

-1

This should work.

function GetLocalizedTerm (itemName, language){
 return new Promise((resolve, reject) => {
         var oReq = new XMLHttpRequest();
       oReq.open("get", "GetLocalizedTermFromDictionary.php?itemname=" + itemName + "&LANG=" + language, true);
   
        oReq.onload = () => {
            if (oReq.status >= 200 && oReq.status < 300) {
                resolve(oReq.response);
            } else {
                reject(oReq.statusText);
            }
        };
        oReq.onerror = () => reject(oReq.statusText);
        oReq.send();
    });
}

async function DisplayItemInCorrectLanguage()
{
        const language='en'
        var str = await GetLocalizedTerm ("CBRAND", language);
        console.log('str: ', str); 
}
Nilesh Patel
  • 3,193
  • 6
  • 12