0

I have an ajax getting values from db, and the result is pushed into an array:

function pushPONFail(dt, ct) {
    if (ct < 12) {
        var tMon =  parseInt(dt.getMonth())+1; 
        var tYear = dt.getFullYear();

        ct++;
    } else {
        return;
    }
    data = {"qType": 101, 
            "tbl": 'qualitypqa.dbo.centerthickness',
            "month": tMon,
            "year": tYear,
            "type": 'Lotrafilcon B'};   
    $.ajax({
      cache : false,
      url: "getrpt.php",
      type: "get",
      data: data,
      contentType: 'application/json; charset=utf-8',
      async: true,
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        console.log("error: "+textStatus+" : "+errorThrown);
      }
    })
    .done(function(response){  
        var obj = jQuery.parseJSON(JSON.stringify(response));
        arrPONFail.push({Month: months[tMon-1]+"/"+tYear, PONFail: obj[0].PONFail});
        dt = new Date(dt.setMonth(parseInt(dt.getMonth()) - 1));
        pushPONFail(dt, ct);
    }); 

} // pushing values such as ["May/2017", 0]

$(function() {
    var dt = new Date();
    pushPONFail(dt, 0);

    console.log(arrPONFail);
});

These are the complete function. When I console.log the array, it came out as my picture. I'm unable to extract the data.

When I print the array into the console, it came out as the picture below.

How do I get the values back out from the array? When I do an arrT[0], I get an undefined.

Please advise.

enter image description here

rherry
  • 95
  • 4
  • You're console logging arrT outside of the .done(). You should console log arrT after done() is completed or you can call timeout function for 1000 millisecond and then log arrT. You will see the difference. – supritshah1289 May 25 '17 at 20:03

1 Answers1

0

This is most likely an asynchronous issue - are you accessing arrT[0] outside of the .done() function? If so, at the time you're accessing it, there is nothing in the array - it's empty. The ajax request you're making takes some time (milliseconds), and only after that data returns does your array have something in it. To use the values in the array, try putting the code that uses the array inside the .done() function itself.

Arnav Aggarwal
  • 769
  • 5
  • 7
  • The thing is, I use a callback system to avoid putting in async: false on ajax. If I do async: false, value is defined correctly. After .done(), I do a console.log(arrT), and I got the picture that I attached, meaning that value is there, right?. Only when I tried to extract the value then I have the undefined. – rherry May 26 '17 at 03:47
  • Try console.logging inside the `done()` function. If you do it outside, you'll run into the async issue, because all code outside the `done()` function runs last. – Arnav Aggarwal May 26 '17 at 16:40