0

I'm trying to generate an array from ajax result. When my code runs it populates the list. But once the ajax call is done, and I start iteration of that populated list, it doesn't output anything.

When I put it in debugging mode I can see that the array "tlitems" is getting populated.

But then after last item is added, it goes out.

var tlitems = [];

function GetTL() {
  $.ajax({
    type: 'GET',
    url: '/PTL',
    datatype: 'json',
    headers: headers
  }).done(function(ptl) {
    $.each(ptl, function(key, value) {
      var pid = this.pid;
      var owner = this.strowner;
      var dbtstamp = this.db_tstamp;
      var tlt = "pi";

      item = {}
      item["_pid"] = personid;
      item["_owner"] = owner;
      item["_dbtstamp"] = dbtstamp;
      item["_tlt"] = tlt;
      tlitems.push(item);
    });
  }).fail();

  $.each(tlitems, function(k, v) {
    alert("Key: " + k + ", Value: " + v);
  })
};

It should alert with K:V. But it just comes out.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Mashhoor Gulati
  • 127
  • 3
  • 13
  • I think your iteration code runs before the done block is executed, trying console logging in both places. – shortCircuit Aug 18 '19 at 12:48
  • 1
    Your iteration logic is fine, the problem is because the AJAX call is asynchronous, hence `tlitems` is still empty when the `$.each()` runs. Simple solution, move the `$.each` inside the `done()` handler. More detail is available in the duplicates I've marked – Rory McCrossan Aug 18 '19 at 12:49
  • @shortCircuit yes I also suspected that during debugging. Bu don't understand the reason and how to resolve. – Mashhoor Gulati Aug 18 '19 at 12:49
  • @RoryMcCrossan OK. But I've few more ajax blocks from which the tlitems needs to be updated. Once its updated finally then only I need to iterate through. So where should I put $.each() in this case? – Mashhoor Gulati Aug 18 '19 at 12:55
  • 1
    In that case put the `$.each()` in a function which you call from `done()`, and pass the `tlitems` array to it as an argument. Do not make it a global variable. – Rory McCrossan Aug 18 '19 at 12:59
  • Since its 2019 use 1. Promises or 2. async/await and life will be easier – shortCircuit Aug 18 '19 at 13:03
  • @shortCircuit can you elaborate.? – Mashhoor Gulati Aug 18 '19 at 13:04
  • 1
    No, already explained https://stackoverflow.com/a/14220323/2974953 . You need to understand the basics of asynchronous nature of javascript and ajax. This is a very common problem. If you replace the `ajax` stuff with a `setTimeout` the reasoning should be same – shortCircuit Aug 18 '19 at 13:11

0 Answers0