1

Have an issue with scope in javascript and cant work out how to pass a value out

$(document).ready(function() {   
  availableTags = new Array();
  $.getJSON('index.php?getTagList', function(data) {
      availableTags = data;
      alert(data);
  });
  alert(availableTags);
});

I know that the data is right and the alert confirms it but how do i assign it to the availableTags variable? seriousli strigling with scope in javascript...

ole
  • 5,166
  • 5
  • 29
  • 57
  • 1
    Not a scope issue; the `getJSON` callback function runs chronologically last. – apsillers May 24 '13 at 14:50
  • Another duplicate: [jQuery async ajax query and returning value problem](http://stackoverflow.com/questions/2931100/jquery-async-ajax-query-and-returning-value-problem-scope-closure) – apsillers May 24 '13 at 14:54

1 Answers1

6

The problem is that the $.getJSON(url, callback) is asynchronous. The callback hasn't executed (and set the availableTags variable) before you try to alert the availableTags variable.

RobH
  • 3,604
  • 1
  • 23
  • 46