Dhaval
Dhaval

Reputation: 89

get variable value in callback function

I have one callback function

function QueryKeyword(keyword, site, callback) {
  var querykeyword = keyword;
  var website = site;

  $.ajax({
    url: "http://www.test.com",
    jsonp: "jsonp",
    dataType: "jsonp",
    data: {
      Query: querykeyword
    },
    success: callback
  });
}

I am calling this function with in for loop like this :

for (i = 0; i < questionTerm.length; i++) {
  for (j = 0; j < site.length; j++) {
    var searchTerm = questionTerm[i] + ' ' + $('#search').val();

    QueryKeyword(searchTerm, site[j], function(reslt) {
      // I need to get j variable value here
      console.log(j);
    });

  }

}

Now I need to get "j" variable value in function see I console the j variable value but it does not get the j variable value.

Would you please let me know how I can fetch the value in this.

Thanks in advance

Upvotes: 1

Views: 593

Answers (2)

Luke
Luke

Reputation: 8407

The problem is, that at the moment of your callback, j was reassigned multiple times to something different.

There are a few options you could do.

  1. call your callback with the params you need

function QueryKeyword(keyword, site, index, callback) {
  // ...
  $.ajax(
      success: function(result) {
          // call the callback with a second param (the index j)
          callback(result, index);  
      }
  )
}

QueryKeyword(searchTerm, site[j], j, function(reslt, param) {
   // param is j
   console.log(result, param);
});

  1. save the var in a closure

(function() {
    var value = j;
    ...
})();

  1. use forEach

questionTerm.forEach((term, i) => {
    site.forEach((s, j) => {
        // we are in a closure, 
        // j will be correct here.
        QueryKeyword(term, s, function(reslt) {
          // j is still correct here
          console.log(j);
        });
    })
});

  1. if you use es6, you could use let keyword. Here is some good explanation, how it works when using for loops

for(let i = 0; i < 10; i++) {
 console.log(i);
 setTimeout(function() {
   console.log('The number is ' + i);
 },1000);
}

Upvotes: 4

dmgig
dmgig

Reputation: 4568

You have to pass it in separately:

definition

function QueryKeyword(keyword, site, index, callback)
{
   ...
}

execution

QueryKeyword(searchTerm, site[j], j, function(reslt) {
   // I need to get j variable value here
   console.log(j);
});

Upvotes: 0

Related Questions