0

I have a problem with array variable scope in Javascript. Here's my code

var features = new Array();
var x = 0;

$.ajax({
  async: true,
  url: domain + "client/applications/getFeatures",
  dataType: 'json',
  success: function(data) {
    if (data.code == 200) {
      $.each(data.data, function(i, val) {
        features[x] = val.features_value;
        x++;

      });
    }
  }
});

alert(features[0]);

The result of the pop up always "undefine". Do you have solutions ? Thank you

Bojan Petkovski
  • 6,835
  • 1
  • 25
  • 34
  • I did, but still the same – MyNameIsAnz Oct 24 '14 at 09:00
  • 3
    since your ajax call is asynchronous, the value of the alert is returned before the ajax call has been completed. Please don't turn the call synchronous, just invoke a callback function in the success method that shows the value. – Fabrizio Calderan Oct 24 '14 at 09:01

2 Answers2

3

You problem isn't with variable scope, it's with async code.

Your alert is fired before the success callback, so features hasn't been set yet. Do something like this instead:

$.ajax({
  // ... other AJAX opts
  success: function(data){
    var features = new Array();
    if(data.code == 200){             
      var x = 0;
      $.each(data.data, function(i, val){
        features[x]=val.features_value;                    
        x++;
      });        

    }
    alert(features[0]);
  }
});
Ahrengot
  • 1,579
  • 1
  • 17
  • 29
1

If you need to use the alert(); (eg, you're not using it for debugging) then you'll need to include it within the success function because it's asyncronous and needs to wait until it gets the response before showing the value!

Dave
  • 8,163
  • 11
  • 67
  • 103