0

I have a global JSON obj array I set in /scripts/globals.js:

var myJSONObj = [];

I am trying to retrieve the content of /scripts/dandylabs_images.json into myJSONObj using two functions:

function doGet(path, callback) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                callback(xhr.responseText);
            } else {
                callback(null);
            }
        }
    };
    xhr.open("GET", path);
    xhr.send();
}

function setGlobalObj(obj) {
    try {
        myJSONObj = obj;
    } catch (e) { 
        console.log("Error in setGlobalObj: " + e.message);
    }
}

I want to ultimately set it to myJSONObj so that my class, JSONRetriever, can eventually use it:

class JSONRetriever {
    
    constructor()  {
        this.init();
    }
    
    getArray() {
        var array = [];
        var myObj = this.getJSON();
        try {
            for (var i = 0; i < myObj.length; i++) {
                array[i] = myObj[i].id + ',' + myObj[i].data.fileName + ',' + myObj[i].data.desc;
            }
        } catch (e) {
            console.log("Unable to parse object array in JSONRetriver.getArray(): " + e.message);
        } 
        
        return array;
    }
    
    getJSON() {
        alert(myJSONObj);  // This always returns empty [] but shouldn't
        if (typeof myJSONObj !== 'undefined' && myJSONObj != null && myJSONObj.length != undefined && myJSONObj.length > 0) {
            console.log('myJSONObj content retrieval successful - locally returning to JSONRetriever.getArray()');
            return myJSONObj;
        } else {
            return JSON.parse(JSON.stringify(imageJSONArray));              // SEE constants.js
        }
    }
    
    init() {
        if (document.URL.startsWith('http')) {
            this.setJSON();                                     // WILL SET GLOBAL myJSONObj - SEE globals.js
        }
    }
    
    setJSON() {
        console.log('Retrieving /pages/scripts/dandylabs_images.json content');
        doGet('/pages/scripts/dandylabs_images.json', setGlobalObj);        // SEE functions.js
    }
    
}

However, somehow, myJSONObj loses its value the moment I return to the class in getJSON() from setJSON() via doGet(). I am unsure as to why this is happening. Please advise, thanks

0 Answers0