I have this AJAX call to a php function from jquery.
On change of a select box I call do the fetching of data (which comes 100% from php).
I then enter the $.each area to process the data into a list.
The list is generates in the txt variable, but its scope is only for the $.each block.
How can I pass it back to the outside (second console.log(txt);)
$('#selectMain').on('change', function(){
var txt = '';
var argument = $('#selectMain').val();
$.ajax({
type: 'POST',
url: './inc/ListManagerScripts.php?argument='+argument,
success: function(json){
var countries = [];
var countries_uuid = [];
data = $.parseJSON(json);
$.each(data, function(key, value) {
//append countries
if($.inArray( value.country_uuid, countries_uuid ) == -1 ){
countries.push(value.country);
countries_uuid.push(value.country_uuid);
var txt = txt + addCountry(value.country, value.country_uuid);
}
console.log(txt);
});
console.log(txt);
}
});
var addCountry = function(country, uuid){
var snip = '';
snip = snip + "<div class='expandListHeader'>";
snip = snip + "<div class='expandListHeaderRow' ctryID='"+uuid+"'>"+country+"</div>";
snip = snip + "</div>"
snip = snip + "<div class='expandListContent'>";
snip = snip + "<div class='expandListContentRow contentCol2'>";
snip = snip + "</div>";
snip = snip + "</div>";
return snip;
}
});
txtbefore the$.eachtxtoutside the$.eachblock already?$.each(as one of the answers states)dataType: 'json'to the ajax call. No json parsing is needed than.