Reputation: 3369
This is my jQuery code. I basically am grabbing some coordinates based on IP and then retrieving some records for the location. The problem I have is that the parameters retrieved from the first ajax call are unavailable to the second ajax call. I am new to deferred's and don't really understand why this is not working? I left some comments in the code as questions and where the problem is. A complete answer would explain what I am missing and why it matters. I am trying to wrap my head around this to make my code cleaner versus nesting the calls.
$(document).ready(function() {
$('#button').on('click', function() {
//if the first call is successful then run the second function
//is done the correct thing to use here?
getLocation().done(getRecords);
});
//this works fine as i get the coordinates
function getLocation() {
return $.ajax({
dataType: "json",
url: 'http://ipinfo.io/json',
success: function(response) {
var coordinates = response.loc.split(',');
return coordinates;
}
});
}
function getRecords(coordinates) {
return $.ajax({
dataType: "json",
url: 'some url',
data: {
//this does not work as coordinates are undefined
lat : coordinates[0],
lon : coordinates[1],
},
success: function(response) {
//do more stuff
}
});
}
});
Upvotes: 0
Views: 37
Reputation: 20229
Your problem that thesuccess
handler's result is not passed to the done
handler. The original response
is passed. You may've wanted then
.
There's absolutely no reason to use jQuery in 2016, though.
Upvotes: 1
Reputation: 95027
To make this work like you expect, you would need to remove success:
and instead use .then
so that you can pass on the value to the next promise in the chain.
function getLocation() {
return $.ajax({
dataType: "json",
url: 'http://ipinfo.io/json'/*,
success: function(response) {
var coordinates = response.loc.split(',');
return coordinates;
}*/
}).then(function (response) {
var coordinates = response.loc.split(',');
return coordinates;
});
}
Upvotes: 3
Reputation: 4113
Your function calls are backward. Try:
getRecords(getLocation());
Upvotes: -2