0

I am trying to execute this code:

    var table = document.getElementById("tab");
    for (var i = 0, row; row = table.rows[i]; i++) {
       //rows would be accessed using the "row" variable assigned in the for loop
       let idd = row.cells[1].textContent;
       
       if(idd != 'Id' && idd != '') {
           $.ajax({
                type: "POST",
                url: "/numordiniperiodoagenti",
                data: {id : idd, start: sstart, end: eend},
                success: function(response){
                    row.cells[10].textcontent = 'p'; //or response as it should be
                }
            });
        }
    }

But it seems that row is inaccessible inside this ajax call.

What am I missing here?

76484
  • 8,498
  • 3
  • 19
  • 30
  • 1
    Post your html markup too. Also, why are you mixing jquery and vanilla JS? – bassxzero Mar 10 '23 at 11:23
  • Your `row` variable changes with each iteration, so in the success: callback it's already changed. Move the `row` to inside the for loop and you'll be ok. – freedomn-m Mar 10 '23 at 11:31
  • This should explain it all: [how do javascript closures work](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work/111111#111111) – freedomn-m Mar 10 '23 at 11:34

1 Answers1

0

Since scope of your variable row is only inside the for loop, the ajax's callback function is another scope, so you could not access variable row inside the ajax's callback. To solve this issue, you could define other variable inside callback function, then assign row value to that new variable.

var table = document.getElementById("tab");
for (var i = 0, row; row = table.rows[i]; i++) {
   //rows would be accessed using the "row" variable assigned in the for loop
   let idd = row.cells[1].textContent;
   
   if(idd != 'Id' && idd != '') {
       $.ajax({
            type: "POST",
            url: "/numordiniperiodoagenti",
            data: {id : idd, start: sstart, end: eend},
            success: function(response){
                var target_row = row; 
                target_row.cells[10].textcontent = 'p'; //or response as it should be
            }
        });
    }
}
Trung Duong
  • 3,475
  • 2
  • 8
  • 9