Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass additional parameter to jquery $.(post) callback function?

Tags:

javascript

I am writing this code where I am sending a sequence of asynchronous post requests by using a loop. When the callback related with the post request is called I want to use the loop variable which I directly cannot use because of javascript scoping rules. The code is like this:

for(i=0;i<10;i++)
{
$.post(url,requestData,function(data,status,xhr){
// use variable i
}

I cannot directly use i due to scoping rules related to callbacks in javascript. So I want to pass 'i' as a parameter to the callback but the documentation says there can be only 3 parameters associated with this callback. Is there any way to pass additional parameter?

like image 801
Kishan Kumar Avatar asked Jun 16 '26 12:06

Kishan Kumar


1 Answers

You can use the variable i inside the callback if i is block scoped. Declare i with let keyword

for(let i=0;i<10;i++)
{
   $.post(url,requestData,function(data,status,xhr){
      // use variable i
   }
}

Here's a demo

const $ = {
  post: function(callback) {
    setTimeout(() => callback(123, 'OK', null), 1000);
  }
}

for(let i=0;i<5;i++)
{
     $.post(function(data,status,xhr) {
         // use variable i
       console.log(i);
     })
}
like image 87
Yousaf Avatar answered Jun 19 '26 02:06

Yousaf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!