hatcyl
hatcyl

Reputation: 2352

jQuery chain ajax calls

I cannot for the life of me understand why this is not working ...

function Register(email, password) {

var data = {
    Email: email,
    Password: password,
    ConfirmPassword: password
};

return $.ajax({
    type: 'POST',
    url: baseUrl + 'api/Account/Register',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify(data)
})

}

function Login(email, password) {

var data = {
    grant_type: 'password',
    username: email,
    password: password
};

return $.ajax({
    type: 'POST',
    url: baseUrl + 'Token',
    data: data
}).done(function (data) {
    sessionStorage.setItem(tokenKey, data.access_token);
});

}

Now ... I want to Register and then Login in one button click ...

var email = $('input[name="email"]').val();
var password = $('input[name="password"]').val();

Register(email, password).then(Login(email, password))

But, that code does NOT call them in order. It does Login first usually.

I have also tried done() and when(), but I honestly do not understand the difference and would love some help ... cries

Upvotes: 0

Views: 387

Answers (2)

Michael C. Gates
Michael C. Gates

Reputation: 992

function Register(email, password) {

    var data = {
        Email: email,
        Password: password,
        ConfirmPassword: password
    };

    return $.ajax({
        type: 'POST',
        url: baseUrl + 'api/Account/Register',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(data),
        success: function(msg) {
            Login(email, password);
        }
    })

}

Upvotes: 1

rdubya
rdubya

Reputation: 2916

I think the problem is that it is evaluating Login(email, password) immediately.

Try: Register(email, password).then(function() { Login(email, password); });

Upvotes: 1

Related Questions