1

I am trying to access row[i] inside of my ajax success: function. Beside my code, I comment on what values I get in the console. My problem is that I am able to access row only if I reference it statically. It seems as though i is untouchable inside of the ajax success/done function. I also reference row dynamically in the data{.. section of the ajax call.

[JS]

row = [{"subid":44,"taskid":16,"payid":1,"locid":2,"mon":3,"tue":0,"wed":2,"thu":0,"fri":0,"sat":0,"sun":0},{"subid":46,"taskid":16,"payid":1,"locid":2,"mon":7,"tue":3.5,"wed":0,"thu":0,"fri":0,"sat":0,"sun":0}];
for(var i = 0; i < row.length; i++){
  console.log(row[i]); // displays object
  $.ajax({
    type: 'POST',
    url: '../fetch/ft-tasks-assigned.php',
    data: { sub: row[i].subid },  // this works
    dataType: 'json',
    success: function(data){
      var tasks = [];
      data = [{"taskid": 16,"title":"Effort Hour Estimate for Detail Engineering &"},{"taskid":"67","title":"Schedule (Gantt or PERT) Update"}];
      for(var j = 0; j < data.length; j++){
        var str = '<option value="'+data[j].taskid+'">'+data[j].title+'</option>';
        tasks.push(str);
      }
      console.log(row[0]);  // displays object
      console.log(row[i]); // displays 'undefined'

    }
  });
}

I have supplied samples of row and the return data from the call.

  • 1
    If you called the main structure `rows` then you could do `let row = rows[i]` and then use `row` from that point forward, no `i` necessary. This code is really cluttered, so you may not need `i` at all, instead `rows.forEach(row => { ... })`. – tadman Jun 27 '19 at 17:46
  • Might be duplicate of https://stackoverflow.com/questions/30734372/access-javascript-variable-inside-ajax-success – Arun Prasat Jun 27 '19 at 17:48

0 Answers0