title: Jquery - Store Ajax jSON response as variable
body: <p>I'm trying to get the result of an ajax request to set in a variable which I can access outside that request. I've tried this <a href="https://stackoverflow.com/questions/905298/jquery-storing-ajax-response-into-global-variable">JQuery - Storing ajax response into global variable</a> but my variable <code>beer</code> remains undefined outside the <code>$.getJSON</code> and <code>$.ajax</code> functions (I tried both).</p>
  
  <p>Here is my code and where I am able to see the results from the <code>console.log(beer)</code>.</p>
  
  <pre><code>var beer;
  $.getJSON(jsonUrl, function (json) {
      beer = json;
      console.log(beer); // returns beer
  });
  console.log(beer); // returns undefined
  
  var beer = (function () {
      var result;
  
      $.ajax({
          url: jsonUrl,
          success: function (data) {
              result = data;
              console.log(beer); // returns beer
  
          }
      });
      console.log(result); // returns undefined
      if (result) return result;
  })();
  console.log(beer); // returns undefined
  </code></pre>