title: Pass variable to function in jquery AJAX success callback
body: <p>I am trying to preload some images with a jQuery AJAX call, but am having real problems passing a (url) string into a function within the success function of the AJAX call (if that makes sense). </p>
  
  <p>Here is my code as is stands:</p>
  
  <pre><code>//preloader for images on gallery pages
  window.onload = function() {
      setTimeout(function() {     
          var urls = ["./img/party/"]; //just one to get started
  
          for ( var i = 0; i &lt; urls.length; i++ ) {
              $.ajax({
                  url: urls[i],
                  success: function(data,url) {
                      $(data).find("a:contains(.jpg)").each(function(url) {                               
                          new Image().src = url + $(this).attr("href");
                      });
                  }
              });
          };  
      }, 1000);
  };
  </code></pre>
  
  <p>One can see my (failed) attempt at passing the url through into the <code>.each()</code> call - <code>url</code> ends up takes the value of increasing integers. Not sure why or what these relate to, maybe the number of jpg files?</p>
  
  <p>...anyway, it should of course take the single value in my original urls array. </p>
  
  <p>Thanks for any help - I always seem to get in a bit of a twist with these callbacks.</p>
  
  <hr>
  
  <p><strong>PROGESS?</strong></p>
  
  <p>So, I mucked around a bit, taking heed of comments from @ron tornambe and @PiSquared and am currently here:</p>
  
  <pre><code>//preloader for images on gallery pages
  window.onload = function() {
      var urls = ["./img/party/","./img/wedding/","./img/wedding/tree/"];
  
      setTimeout(function() {
          for ( var i = 0; i &lt; urls.length; i++ ) {
              $.ajax({
                  url: urls[i],
                  success: function(data) {
                      image_link(data,i);
                      function image_link(data, i) {
                          $(data).find("a:contains(.jpg)").each(function(){ 
                              console.log(i);
                              new Image().src = urls[i] + $(this).attr("href");
                          });
                      }
                  }
              });
          };  
      }, 1000);       
  };
  </code></pre>
  
  <p>I tried putting the <code>image_link(data, i)</code> here there and everywhere (in each nested function etc.) but I get the same result: the value for <code>i</code> is only ever logged as 3. I suspect that this is because all references to <code>i</code> point to the same thing and by the time the asynchronous task actually gets to <code>image_link(data, i)</code> the <code>for...</code> loop is over and done with (and hence has a value of 3). Needless to say this gives <code>urls[i]</code> as 'undefined'.</p>
  
  <p>Any (more) tips how I can get round this? </p>