2

I am trying to loop through 2 json files. So I created function. The results of this function is being pushed in 'response' array. But when I try to log the length of the array, it returns 0. It seems that the array is empty but when I check my console, it show results.

Here's my current code:

var response = [];
    function getJSON(server, orgid) {

        const xhr = new XMLHttpRequest();
        xhr.open('GET', 'https://pr.site.workers.dev/?'+server);
        xhr.responseType = 'json';
        xhr.onload = function(e) {
            b = xhr.response

            for (var i in b){
                response.push([b[i]][0]);
            }
        };
         xhr.send();

    }


    $(document).ready(function() {  

    arone = getJSON('https://www.chamberorganizer.com/members/mem_xml/BLVR_members.json','');
    artwo = getJSON('https://www.chamberorganizer.com/members/mem_xml/SFCC_members.json','')

    console.log(response);

Here's the result of the array: array collapsed array expanded with results

thewebyogi
  • 23
  • 2
  • 1
    console.log runs before the ajax calls are made. That is how Asynchronous calls work. – epascarello May 26 '20 at 20:44
  • Thanks. I'm a beginner with javascript. Can you tell me how I can Ioop through the results because the code here is not showing me anything. Been on it for hours and nothing worked. I'm trying to get the categories. It looks like the array is empty. – thewebyogi May 26 '20 at 20:50
  • You ordered a pizza and you try to eat the pizza as soon as you hit the enter button. You are not waiting for it to be delivered. Look at the second example in my answer https://stackoverflow.com/a/62028273/14104 – epascarello May 26 '20 at 20:54

0 Answers0