0

I have this code:

var myOptions = '<option value=""></option>';
$.getJSON("/users/GetUserAccesses/" + username, function (UserAccesses) {
  $.each(UserAccesses, function (key, val) {
    $.getJSON("/users/GetCommunities", function (Communities) {
      $.each(Communities, function (key1, val1) {
        if (parseInt(val1.id) == parseInt(val.community)) {
          myOptions = myOptions + '<option selected="selected" value="' + val1.id + '">' + val1.name + '</option>';
        } else {
           myOptions = myOptions + '<option value="' + val1.id + '">' + val1.name + '</option>';
        }
     });
   });
 });
});
alert(myOptions);

The alert is returning <option value=""></option>? What am I missing? I have placed the alert in different places before the }) and the results are shown.

Casey Falk
  • 2,617
  • 1
  • 18
  • 29
user3662697
  • 147
  • 1
  • 7
  • 1
    Put the alert inside the callback of the inner `getJSON` call. – Achrome Jul 15 '14 at 20:33
  • 1
    This isn't so much an issue with scoping as with timing on asynchronous operations. The function you pass in to `GetJSON` is a *callback* function which gets called after the asynchronous operation is complete. But the GetJSON itself will finish executing before the callback gets invoked. So the `alert()` call runs before you've received information back from the server. – StriplingWarrior Jul 15 '14 at 20:34
  • I have read this http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call but I am still puzzled on how I can implement it on my code. – user3662697 Jul 16 '14 at 14:22

0 Answers0