0

I've been trying to convert my php code into Ajax Calls since i want my pages to work on Phonegap, unfortunately my expertise with ajax is not stellar and i'm having issues nesting Ajax calls:

The first ajax call works well (it returns a JSON), and the second is working as well, but i'm not able to save the result in order to fill the loop in the first one. areaname is always empty. It shows when i alert it, i'm just not able to use it in my array push.

I'd also like to know if it's a healthy approach, or is there a better way to convert php code (at least the logic).

Here's the code:

$(document).ready(function(){

$.ajax({                                      
  url: 'ajax/getcountries.php',                      
  data: "",                                                        
  dataType: 'json',                     
  success: function(requests){

    var countries = [];

    $.each(requests, function (key, value) {

      var areaname = '';

        $.ajax({                                      
                  url: 'ajax/getareas.php',                      
                  data: "areaid=" + value.area,                                                                            
                  success: function(a){
                    areaname = a;
                }
        });

        countries.push("<div>" + value.countryname + " <h4>"+ areaname +"</h4></div>");
//areaname is always empty, knowing that i get a good response if i alert "a"


    });  

   $('#countries').html(countries.join(''));
   $('#countries').enhanceWithin();
  } 
});

});

Thank you

j_o_e
  • 99
  • 1
  • 2
  • 8
  • i'm assuming that i'm not allowed to do this, i should have a callback function, but thing is, in my push, i have data from my JSON (first Ajax), and data from my second ajax. – j_o_e Apr 04 '15 at 20:03
  • @Musa, on the contrary, i'm not asking how to get the response, as this is working perfectly. I'm asking how to use variable in more than one place, assuming i have 2 nested ajax calls. – j_o_e Apr 04 '15 at 20:03
  • That question addresses your problem. – Musa Apr 04 '15 at 20:06

0 Answers0