scott21493
scott21493

Reputation: 1

javascript/jquery - object not able to itereate

So, I got an object from a php page that spits out JSON that I have. When I set a global variable equal to an object I create out of it and then try to get the data with a for(key in obj) loop it doesn't seem to work.

If I surround the for loop with something like a random $.post it works. I am so confused as to why this happens.

Here's my code:

var myObj1 = new Object;

$(document).ready(function() {
$.post('namenums.php', {num : 1}, function(data) {
    var temp = $.parseJSON(data);
    for(var key in temp) {
        myObj1[key] = temp[key]['firstname'] + ' ' + temp[key]['lastname'];
    }
});

getStuff();
thing();
});

function thing() {
    for(var key in myObj1) {
        console.log(key);
    }
}

Now if I change my thing() function to something like this it works.

function thing() {
        $.post('random.php', function(data) {
    for(var key in myObj1) {
        console.log(key);
    }
        });
}

So, could someone please explain why this happens?

Upvotes: 0

Views: 43

Answers (1)

rjz
rjz

Reputation: 16510

Sure. In the first example, thing() is being called when the document is ready--not necessarily after the AJAX call initiated by $.post has completed. In the second example, you aren't trying to log anything until the AJAX request is over, done, and results have been returned.

You could fix the first example by moving your call to thing() inside the callback provided to $.post:

$(document).ready(function() {
  $.post('namenums.php', {num : 1}, function(data) {
    var temp = $.parseJSON(data);
    for(var key in temp) {
      myObj1[key] = temp[key]['firstname'] + ' ' + temp[key]['lastname'];
    }
    thing();
  });

  getStuff();
});

Upvotes: 1

Related Questions