Anik Anik - 1 year ago 70
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

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.
var p = document.getElementById("postCode").value;
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
data:$.param({lat: lat, lng:lng}),
return false;

Answer Source

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download