Brock Adams
Brock Adams

Reputation: 93453

How can I pass a parameter to the callback of a jQuery ajax request?

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?

Upvotes: 3

Views: 481

Answers (1)

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

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.

Upvotes: 5

Related Questions