I am having a difficult time understanding the scope of some vars in javascript. in the below code - I want to make an ajax call, and loop over my results creating some html elements that get populated a it later...also in that original loop I want to populate an array that I'll use later.
when i fist wrote it I created the array in the .done function, but I got an undefined when testing it for .length ( things_ids.length ) later. So i moved it up to the calling function, but it's still undefined when i go to use it later.
...
var things_ids = [];
$( '.filter' ).click( function() {
$.ajax({
method: 'POST',
url: 'list.html',
data: { ... },
dataType: 'json',
cache: false
})
.fail( function( jqXHR ) {
$( '#msg' ).append( '...fail msg...' + jqXHR.responseText + ' ' + jqXHR.statusText );
})
.done( function ( data ) {
// html back to user
var divs = '';
if ( data['DATA'].length ) {
for ( var i = 0; i < data['DATA'].length; i++ ) {
divs += '<div class="header" >' + data['DATA'][i][1] + ' <span class="toggle-thing" >( show )</span></div>\
<div class="container" id="thing_' + data['DATA'][i][0] + '" ></div>';
things_ids.push( data['DATA'][i][0] );
}
} else {
divs = '<div>We have no data.</div>';
}
// populate the select
$( '#things_container' ).html( divs ).slideDown( 3000 ).fadeIn( 1000 );
});
// here's where it goes wonky for me
alert( 'thing id : ' + things_ids ); // this show nothing
// here i want to load data to the newly created divs
if ( things_ids.length ) {
for ( var t = 0; t < things_ids.length; t++ ) {
alert( 'thing id : ' + things_ids[g] );
$( '#thing_' + things_ids[t] ).hide(); // start by hiding the div - toggle later....
// spinner
$( '#thing_' + things_ids[t] ).html( '<img src="spinner.gif" alt="data loading" />' );
// content
$( '#thing_' + things_ids[t] ).load( '/things', function( response, status, xhr ) {
if ( status == 'error' ) {
var msg = 'Sorry but there was an error loading the thing: ';
$( '#thing_' + things_ids[t] ).html( msg + xhr.status + ' ' + xhr.statusText );
}
});
}
}
});