0

I have an array declared in an else structure

var days = new Array();
$.ajax({
      url: 'someurl',
      dataType: 'jsonp',
      success: processJSON
});

I process the data from the ajax call in the processJSON function

function processJSON(jsonData) {
    var weather = jsonData.data.weather;
    for(var key in weather) {
        var day = weather[key];

        days.push(new Array(day.tempMaxC, day.type));
    }
}

I add some other arrays to the days-array.

If I check it in the console (in the processJSON-function), the length is three/

Then when I want to use the variable in some code under the the ajax-call, nothing works and when I check the length it's 0. I guess it's something with declaration?

Csharp
  • 2,916
  • 16
  • 50
  • 77
Veltar
  • 741
  • 2
  • 14
  • 30
  • 2
    AJAX is **asynchronous**, so when you say you want to use it in code under the AJAX call, it most likely hasn't been populated yet. Do what you need to do with it inside your `processJSON` event, or add another callback. – tymeJV Jul 31 '13 at 16:08
  • … and see [JavaScript console lazy about evaluating arrays?](http://stackoverflow.com/questions/4057440/is-chromes-javascript-console-lazy-about-evaluating-arrays) on why you see it in the console. – Bergi Jul 31 '13 at 16:21

3 Answers3

1

Is your code under the Ajax call happening after the processJson function? The call to the ProcessJson function is asynchronous and happens only after the Ajax call finishes. However the code following it might happen before. So it might be a timing thing. If you need the array for any other processing you should have it in the callback or after you know the callback has been finished.

Deepak
  • 353
  • 5
  • 14
0

Put the declaration outside of the condition/else

var days = new Array();
if(...){
}else{
$.ajax
}
Lwyrn
  • 1,821
  • 1
  • 16
  • 27
0

You need to wait until the XHR call has finished. It looks like you're using JQuery so check out their deferred docs (http://api.jquery.com/deferred.then).

You would end with something like this:

$.ajax({
      url: 'someurl',
      dataType: 'jsonp'
}).then(function( jsonData ) {
    var weather = jsonData.data.weather;
    for(var key in weather) {
        var day = weather[key];
        days.push(new Array(day.tempMaxC, day.type));
    }        
    console.log( 'done!', days );
});
voidstate
  • 7,937
  • 4
  • 40
  • 52
  • He *does* wait with `processJSON` after the call finished. You should focus on the thing that does not wait… – Bergi Jul 31 '13 at 16:23