0

I have been facing a problem of which I am unable to call a .length() method to a data array in javascript. The purpose is to be able to iterate through an array of date time string in order to convert them to date objects in javascript. Here is my code.

My data:

HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
  "sales_time_axis": [
    [
      "2019-12-29T10:42:25Z"
    ],
    [
      "2019-12-23T03:13:03Z"
    ],
    [
      "2019-12-23T02:50:51Z"
    ]
  ],

The ajax call:

$.ajax({
  type: "GET",
  url: endpoint,    
  success: function(data) {
    window.sales_time = data.sales_time_axis
  },
  error: function(error_data) {
    console.log('error')
    console.log(error_data)
  }
})

The for loop:

var sales_time;
var date_array = []

for(i = 0 ; i < sales_time.length ; i++){
  date_array.push(new Date(sales_time[i]))
}

console.log(data_array)

I have declared sales_time as a global variable , however I'm getting this error:

(index):179 Uncaught TypeError: Cannot read property 'length' of undefined
at (index):179

Your help will be greatly appreciated!

Ampersanda
  • 2,016
  • 3
  • 21
  • 36
noobmaster64
  • 85
  • 2
  • 10
  • also you need to global variable is array like `var sales_time=[];` – kelvin kantaria Dec 31 '19 at 05:20
  • @kelvinkantaria—an array is assigned in the callback, the issue is the asynchronous call. Initialising *sales_time* as an empty array would remove the error but wouldn't fix the asynchronous issue. – RobG Dec 31 '19 at 23:05

3 Answers3

0

Probably you are facing an asynchronous variable assignment problem. Try to put the for-loop together with the success callback and iterates over the same sales_time variable that are being received on the callback parameter.

$.ajax({
  type: "GET",
  url: endpoint,    
  success: function(data){
    var sales_time = data.sales_time_axis;
    var date_array = []
    for(i = 0 ; i < sales_time.length ; i++){
      date_array.push(new Date(sales_time[i]))
    }
    console.log(data_array)
  },
  error: function(error_data){
    console.log('error')
    console.log(error_data)
  }
})
Pedro Mutter
  • 1,178
  • 1
  • 13
  • 18
  • yes placing the for loop into the ajax function works out fine , however i still need to be able to take this date_array out of the ajax success callback inorder to be able to manipulate my graph , do u have an idea of how to do that? – noobmaster64 Dec 31 '19 at 02:46
  • You will need to call another function inside the callback to update your graph. Another approach would be with an event listener. You make the graph update on the listener then you fire this event on the success callback, passing the date_array as the parameter. – Pedro Mutter Dec 31 '19 at 20:15
0

you need to wait the ajax call first,since it is async

take a look at following link: How to await the ajax request?

rizesky
  • 424
  • 6
  • 13
0

As others had pointed out, ajax is an async process. Anything outside of the ajax run synchronously, meaning it won't wait for your data to come. One way you can do this is by putting the iteration method as a callback inside ajax success method with the data as its argument.

$.ajax({
    // SOME CONFIGS HERE
    success: function(result){
        iterate(result);
    }
});

function iterate(data){
    // Do your iteration here
}

Or if you insists on the global variable thingy, then you can do it like this

// Assuming all these are inside the same javascript file

var data = []; // Make this a global value inside your file 

$.ajax({
    // SOME CONFIGS HERE
    success: function(result){
        data = result.data;
        iterate(); // Get data, then hit the iterate process
    }
});

function iterate(){
    // Do your iteration here
    data.forEach(() => { // Some process in here });
}

This method will call on the iterate ONLY after the call has successfully finished. Don't try to call iterate outside the success method or you will for sure get an empty array.

Your mindset in writing code have to change if your flow depends on a promise to be finished first. You need to execute your next step only after the promise has resolved, not simply running it while the promise still not resolved.

Fred A
  • 1,602
  • 1
  • 24
  • 41