user2951535 user2951535 - 7 months ago 25
Javascript Question

How to set the global array values inside another function call

I am using ajax call to retrieve the values from database and then trying to insert those values into arrays(declared globally).But Outside the called function if I am trying to check the value of arrays it is showing empty arrays. Here is the my code:



function functionName() {

var arr1 = [];
var arr2 = [];

$(function() {

$.ajax({
url: "RandomURL",
data: {
some random data
}
}).done(
function(data) {
console.log(data.data);

for (var i = 0; i < data.data.length; i++) {
arr1.push({
x: data.data[i][0],
y: data.data[i][1]
});
arr2.push({
x: data.data[i][0],
y: data.data[i][2]
});
}

});

});
console.log(arr1);
console.log(arr2);

return [{
values: arr1,
key: 'array1 values',
color: '#ff7f0e'
}, {
values: arr2,
key: 'arr2 values',
color: '2ca02c'
}];

}




Answer

Just change as below, you do not need to return these array to another function as you have declared it as global below:

    var arr1 = [];
    var arr2 = [];

    function functionName() { 

    $.ajax({
          url: "RandomURL",
          data: {
            some random data
          }
        }).done(
          function(data) {
            console.log(data.data);

            for (var i = 0; i < data.data.length; i++) {
              arr1.push({
                x: data.data[i][0],
                y: data.data[i][1]
              });
              arr2.push({
                x: data.data[i][0],
                y: data.data[i][2]
              });
            }

          });

      console.log(arr1);
      console.log(arr2);


    }

So you can assign values in plod data like:

var plotData = [{
    values: arr1,
    key: 'array1 values',
    color: '#ff7f0e'
  }, {
    values: arr2,
    key: 'arr2 values',
    color: '2ca02c'
  }];
Comments