title: jQuery: how to make a global variable accessible within $.ajax()
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/4614714/cant-access-global-variable-in-jquery-get-within-function">Can&#39;t access global variable in jQuery $.get within function</a>  </p>
  </blockquote>
  
  
  
  <p>This is probably a newbie problem, but here it goes: I declared a global variable called preview. With AJAX, I get a json array and loop through it. For each iteration, I do another AJAX call to get a string and append it to the global variable.</p>
  
  <p>However, printing the global variable after the second AJAX call gives me "empty string" (I am definitely getting a string back from the second AJAX call).</p>
  
  <p>Here's the code:</p>
  
  <pre><code>var preview;
  $("#some-button").click(function(e){
      e.preventDefault();
      var companies = "blahblahblah";
  
      $.ajax({
          url: "tracklink/getemails.php",
          type: "POST",
          data: "companies=" + companies,
          dataType: "json",
          success: function(databack) {
              if (databack) {
                  for (i=0; i&lt;databack.length; i=i+1) {
                      preview = "";
                      $("#selected-clip-list li").each(function(){
                          $.ajax({
                              url: "tracklink/cksum.php",
                              type: "POST",
                              data: "video_id=" + $(this).attr("clip_id") + "&amp;addr=" + databack[i].email_address,
                              success: function (msg) {
                                  if (msg) {
                                      preview += msg;
                                  }
                                  //this works
                                  //console.log(preview);
                              }
                          });
                      });
                      //doesn't work
                      console.log(preview);
                  }
              }
          }
      });
  });
  </code></pre>
  
  <p>Any idea why I'm getting "empty string"?</p>
  
  <p>Many thanks.</p>