2619 2619 - 1 month ago 7
Ajax Question

Chained ajax request with jquery promise

I have following code. What I am doing is that first I make an ajax request to first url. I get a response and I need some data from that response. For that reason, I put that data into

user
object. That response also include another url. Then I make another ajax request to that new url. And I get response from the url and I add that data to
user
object. In the last
then()
function I return
user
object. However, when I call
get().done(function(data) { console.log(data) })
, I only get
user.data
array only. It does not include user's detail in first ajax request. How can I merge the data from these two requests and return as a promise(deferred maybe)?

var get = function() {
var user = {};

return $.ajax({
url: 'URL',
method: 'GET',
type: 'JSON'
}).then(function(user) {
user['name'] = user.name;
user['joined'] = user.create_at;

return $.ajax({
url: user.url,
method: 'GET',
type: 'JSON'
});
}).then(function(data) {
user['data'] = data;
return user;
});
},

Answer

In this function

function(user) {
    user['name'] = user.name;
    user['joined'] = user.create_at;

    return $.ajax({
        url: user.url,
        method: 'GET',
        type: 'JSON'
    });
}

You are creating a user variable in the function's local scope. So when you do user['name'] = user.name;, on the left part of the assignment, you are not referring to the var user = {} you defined outside, at the highest scope, but to the local user.

Try naming the fetched user data something else, like userData