1

I'm having trouble getting the value of a variable I calculate elsewhere to work in another function. I know I'm missing something obvious, but not sure what. Here's what my code looks like:

var total_count;    
    function getDistances() {
    $.getJSON('https://something.com', function(data){
       var total_count = data.rows[0].count; //this is the correct value for total_count
    });
    $.getJSON('https://anotherthing.com', function(data){
      d1_1 = [];
      var limit = 4;

       $.each(data.rows, function(index, item){
         if(index > limit) 
           return false;
         console.log(total_count); //This is undefined  
         d1_1.push([Math.round((item.count/total_count*100)*100)/100,index]);
         //because total_count is undefined here, I get NaNs
       });
   });
Sarath Chandra
  • 1,850
  • 19
  • 40
jonmrich
  • 4,233
  • 5
  • 42
  • 94

3 Answers3

1

You can do something like below.

function getDistances() {
    $.getJSON('https://something.com', function (data1) {
        var total_count = data1.rows[0].count;
        $.getJSON('https://anotherthing.com', function (data) {
            d1_1 = [];
            var limit = 4;

            $.each(data.rows, function (index, item) {
                if (index > limit) return false;
                console.log(total_count);
                d1_1.push([Math.round((item.count / total_count * 100) * 100) / 100, index]);
            });

        });
    });
ashokd
  • 393
  • 2
  • 11
0

You need to undeclare total_count a second time:

var total_count = data.rows[0].count;//var total_count has been declared

change to

total_count = data.rows[0].count;
depperm
  • 10,606
  • 4
  • 43
  • 67
0

You've already declared total_count outside of

function getDistances() {
$.getJSON('https://something.com', function(data){
              var total_count = data.rows[0].count; //this is the correct value for total_count
    });

Because of the scope change, the value gets assigned to the inner total_count rather than the outer one.

So in summary, the code should be:

var total_count;    
function getDistances() {
$.getJSON('https://something.com', function(data){
              total_count = data.rows[0].count; //this is the correct value for total_count
    });  
m27
  • 79
  • 1
  • 9