Click here to Skip to main content
15,868,141 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am runing a ajax post back call in loop its work fine if I not use variable 'i' after post back but I want to use it to get row.cell data from HTML table. how to do this Here is my code and error is in this line.
myTab.rows[i].cells[4].children[0].value = result.ST;

the full code is .
JavaScript
function FW(c) {
    //if (((c.which || c.keyCode) == 9) || ((c.which || c.keyCode) == 13)) {
    var myTab = document.getElementById('TB1');
    var CTCValue = $('#txtCTCValue').val();
    event.preventDefault();
    for (i = 1; i < myTab.rows.length; i++) {
        $.ajax({
            url: '/Master/salaryscheme/GetFarmulaCalculation?FW=' + myTab.rows[i].cells[3].children[0].value + '&CTC=' + CTCValue,
            type: 'GET',
            error: function (xhr) {
                alert('Error: ' + xhr.statusText);
            },
            success: function (result) {
                if (result.ST != "") {
                   
                    myTab.rows[i].cells[4].children[0].value = result.ST;
                    //alert(result.ST)
                }

                $('#divSearchResult').text = "";
                $('#divSearchResult').html(result);
                document.getElementById("P1").click();
            }
        });

    }
     
    //}
}


What I have tried:

var i =1; I tried to define i but it's not working.
Posted
Updated 14-Dec-20 2:13am
v2

1 solution

You've captured a variable which is modified before your AJAX callbacks fire.

In a modern browser, you could use let to make a block-scoped copy of the loop variable inside the loop, and use that instead:
JavaScript
for (let i = 1; i < myTab.rows.length; i++){
    let rowIndex = i;
    $.ajax({
        ...
        success: function(result){
            if (result.ST != ""){
                myTab.rows[rowIndex].cells[4].children[0].value = result.ST;
            }
            ...
        }
    });
}
let - JavaScript | MDN[^]

For older browsers, an immediately-executed function would accomplish the same thing:
JavaScript
for (var i = 1; i < myTab.rows.length; i++){
    (function(rowIndex){
        $.ajax({
            ...
            success: function(result){
                if (result.ST != ""){
                    myTab.rows[rowIndex].cells[4].children[0].value = result.ST;
                }
                ...
            }
        });
    })(i);
}
 
Share this answer
 
Comments
Asif 7969814 14-Dec-20 8:39am    
thanks a lot for the quick help you save my day.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900