3

I need to pass extra variables to a jQuery, ajax callback function.

For example, given:

while (K--)
{
    $.get
    (
        "BaseURL" + K,
        function (zData, K) {ProcessData (zData, K); }
    );
}

function ProcessData (zData, K)
{
    console.log (K);
}

ProcessData() will report 0 every time (or whatever the last value of K was).

How do I ensure that ProcessData() fires with, or can get, the correct value of K?

Is there any way to do this without wrapping the $get() in a function?

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
  • Stopping back a moment, why are you doing so many requests, and what is this variable for? Are you keeping track of when the last requests finishes or something? – Nick Craver Jul 05 '10 at 22:17
  • @Nick Craver: I'm doing so many requests because I need to scrape select information from several pages of a given type. The K, in this case is to track page order, so that the results can be sorted (async requests don't always return in order). There may be other variables, too. ;-) – Brock Adams Jul 05 '10 at 22:21
  • It would be better to do this server-side, a single request coming back...this will be a much better user experience, especially for high-latency clients, something you don't see the effects of when developing. – Nick Craver Jul 05 '10 at 22:25
  • @Nick Craver: Ah, but you assume that I have any control over the servers in question, I do not. This is for a kind of "mash-up" application from disparate sources, none have API's. Also, you propose a "turtles all the way down" approach. SOMETHING has to query all those pages while the user waits. In this case, repeat requests are rare, so server-side caching would be almost useless, where as client browser cache speeds things nicely. Finally, I'd have to set up a web-app instead of a simple extension. Not cost-effective for my purposes. – Brock Adams Jul 05 '10 at 22:33
  • This is a duplicate: http://stackoverflow.com/questions/939032/jquery-pass-more-parameters-into-callback – atp Jul 05 '10 at 22:34

1 Answers1

5

No. Because of the ways closures work, all the inner functions will close over the same K variable (which ends up equalling 0). You need an additional level of indirection somewhere to create separate scopes. E.g.:

while (K--)
{
    (function(K)
    {
      $.get
      (
          "BaseURL" + K,
          function (zData, status) {ProcessData (zData, K); }
      );
    })(K);
}

Also, the second parameter of the success function shouldn't be called K. That parameter will get the status, which would then shadow the desired K.

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539