user1692342
user1692342

Reputation: 5237

calculating sum of values after combining results of multiple AJAX calls.

I am trying to write a JS function which calculates the sum of all visible rows in a column in a table. The way the values in the column is filled is by making multiple ajax calls (50 rows at a time).

I am trying to keep track of no of requests sent and when I receive all responses back calculate the sum.

function onClickofCalculateButton() {
    var noOfRequestsSent = 0;
    var sum = 0;

    var sucCallback = function(response) {
        updateColumn(response, noOfRequestsSent, sum);
    };

    //Some logic to send requests 50 rows a time and I increment the value of noOfRequestsSent;
}

in my updateColumn function()

function updateColumn(response, noOfRequestsSent, sum) {
    noOfRequestsSent--;
    //Do some logic to retrieve value of each row and add it to sum
    if(noOfRequestsSent == 0) {
        alert(sum);
    }
}

However what is happening is the value of noOfRequestsSent is always equal to the actual number of requestssent even after subtracting it in updateColumn function. So it never reaches the condition where noOfRequestsSent == 0 and neither does the sum get added onto the previous value.

I guess I have to pass some object reference or something like pointers in C but I am unable to figure out how to do in JS.

Upvotes: 2

Views: 213

Answers (1)

Dinesh undefined
Dinesh undefined

Reputation: 5546

You could try like this. Since you want to send variable as reference. In this way you can avoid global variables.

function onClickofCalculateButton() {
    var noOfRequests = {
                       sent:0
                       };
    var sum = 0;

    var sucCallback = function(response) {
        updateColumn(response, noOfRequests, sum);
    };

    //Some logic to send requests 50 rows a time and I increment the value of noOfRequestsSent;
}


function updateColumn(response, noOfRequestsSent, sum) {
    noOfRequests.sent--;
    //Do some logic to retrieve value of each row and add it to sum
    if(noOfRequests.sent == 0) {
        alert(sum);
    }
}

Upvotes: 1

Related Questions