[Solved] Javascript Using AJAX to return a JSON Object

I’m trying to use AJAX (through jQuery) to return a bit of JSON from an API, and then store that JSON in localStorage as a string. Whenever the function runs, I want it to check localStorage for the key, and return that value if it exists. If it does not exist, then it should contact the API for the object, save it to localStorage, and then return it.

The problem that I’m having is this: the function NEVER returns the JSON object the first time (when it’s not stored in localStorage). It has no problem saving it to localStorage, and it always pulls it from localStorage just fine, but even right after using the returned object in the previous line, the function won’t return it. The console just says “undefined”.

The code I’m using is below (edited slightly since the API is private):

window.get_company = function() {
    var full = window.location.host;
    var parts = full.split('.');
    var subdomain = parts[0];

    if ( localStorage.getItem("company_" + subdomain) === null ) {
        $.getJSON("https://api.testingapp.com/subdomains?name=" + subdomain).then( function(data) {
            localStorage.setItem("company_" + subdomain, JSON.stringify(data));
            return JSON.stringify(data);
        });
    } else {
        return localStorage.getItem("company_" + subdomain);
    }
}

Thanks so much for your help!

Read more here: Source link