ajax - Referring to parent loop from a nested loop -


here's i'm trying achieve: have 2 tables in db - 'regions' , 'distributors', both have region_id column. want, to:

1) iterate through 'regions' table, each region create div region_id div id, append region_name div.

2) have nested loop, iterate through 'distributors' table, pull distributors has same region_id , append same div stage 1.

so tried code:

$(function(){     $.getjson("inc/api.php", {command:"get_regions"},         function(result){             var div_length = 786/result.length;             for(var i=0; i<result.length; i++){                 var div_name = "div_region_"+result[i].region_id;                 $("<div id='"+div_name+"' class='div_region'                      style='width:"+div_length+"px; float:right;'></div>").appendto("#content");                  $("<b>"+result[i].region_name+"</b></br>").appendto("#"+div_name);                 $.getjson("inc/api.php", {                     command:"get_distributors",                      region_id: result[i].region_id                 },                 function(result){                     for(var j=0; j<result.length; j++){                         $("#"+div_name).append(result[j].distributor_name+"</br>");                     }                 });             }      }); }); 

though creates divs , appends region names them, distributors names appended last div @ moment. where's mistake here , how can fix it?

that's because loop has completed before ajax function returns.

change second ajax function to:

$.getjson("inc/api.php", {         command:"get_distributors",          region_id: result[i].region_id     },     function(result){         for(var j=0; j<result.length; j++){             var id = "#div_region_"+ result[j].region_id; //assuming that's how data structured             $(id).append(result[j].distributor_name+"</br>");         }     }); 

Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

java - Using an Integer ArrayList in Android -