Writing Nested ajax requests

Writing Nested ajax requests

I had not come to this need before. But yes I came to a situation where it felt like there was a need of using the values returned by an AJAX request and do another AJAX request and return the values. Actually this thing came my way while I was writing a modules of YellowPages. There I had this issue. When I select a country in a dropdown, then zones will be populated in another dropdown and the selected dropdown in zones will make another dropdown to pull the districts of the default selected zone. For this I had to use nested AJAX requests. May be this might not be the best way to do this. But yet, it works for me and you might give a try if you are thinking of something similary

$(document).ready(function(e) {
$('#country_id').change(function(){
var id = $(this).val();
$.ajax({
type:"POST",
url: getLocation(),
data: 'action=getZones&id='+id,
success: function(msg){
var zones=JSON.parse(msg);
var zone_content=""
for(var i=0;i<zones.length;i++){
zone_content+="<option value=\""+zones[i].zone_id+"\">"+zones[i].zone_name+"</option>"
}
document.getElementById('zone_id').innerHTML = zone_content;
$.ajax({
type:"POST",
url:getLocation(),
data:'action=getDistricts&id='+zones[0].zone_id,
success:function(msg1){
document.getElementById('district').innerHTML=msg1;
}
});
},
error: function(){} }); }); }); 

The response are json responses. The first response gives zones details which has zone_id, zone_name. And the first zone is taken as the default selected zone to populate the districts.

Comments

Popular posts from this blog

Automate file upload in Selenium IDE

How To Install and Configure Nextcloud