Anik Anik - 2 months ago 13
jQuery Question

nested Ajax response data acess not working

I am beginner at javascript , I am trying to calculate distance between two postcodes.

I am using a REST api with ajax get method to get latitude and longitude of a post code then send another ajax call to a servlet which returns the distance in json format.

Now I am having a hard time accessing the returned json string. When i check what's inside the

data
variable i only find the json elements returned on the first call. But when I check on my browser i find both of the ajax called successfully returned and i can see the json string of second ajax which returned the distance in browser console.

nested ajax returns following

{"distance":"0.005011484329483577"} (found it from browser inspect element console)


I need to be able to store the value of distance into a variable.I tried using data.distance. but it returns undefined.

maybe scope problem?

please help





/*
* Nurul Alam
* and open the template in the editor.
*/
$(document).ready(function(){
$('#PostCodeLookUp').submit(function(){
var p = document.getElementById("postCode").value;
$.ajax({
url:'http://api.postcodes.io/postcodes/'+p,
type:'GET',
dataType:'json',
//data:$('#updateUserName').serialize(),
success:function(data){
if(data){
var lat = data.result.latitude;
var lng = data.result.longitude;
//send the data in a ajax call to a servlet which process the data and returns the distance
$.ajax({
url:'postCodeConverterServlet',
type:'POST',
dataType:'xml',
data:$.param({lat: lat, lng:lng}),
success:function(){
alert(data.distance);
}
});
//
//$('#displayName').html(d);
//$('#displayName').slideDown(500);
}else{
$('#displayName').html("Problem");
}
}
});
return false;
});
});

Answer

In the success function of your second ajax call, you are accessing the return from the first again by using data. Change your second ajax success function to the below giving it its own parameter name for its own response, then use that. You can give the argument a more meaningful name if you'd like but this would work:

success:function(nestedData){
    alert(nestedData.distance);  
} 
Comments