I am trying to send a request in AngularJS to get a token for user registration. Once I get the token, I am sending another request using the token to register the user.
However the first request works and I get the token, but the second one does not work.
Code
facebookExample.controller('registerController', function($scope, $http, $localStorage, $location) {
$scope.data = {};
$scope.getToken = function() {
$http.post('http://you-serve.org/api.php?action=createaccount&format=json&name=' + $scope.data.username + '&email=' + $scope.data.email + '&realname=' +
$scope.data.firstname + ' ' + $scope.data.lastname +
'&mailpassword=false&reason=Fun_and_profit&language=en&token').then(
function(response) {
return response.data.createaccount.token;
}
// End success
,
function() {
alert('error');
} // End error
); //End then
} // End getToken
$scope.register = function(myToken) {
$http.post('http://you-serve.org/api.php? action=createaccount&format=json&name=' +
$scope.data.username + '&email=' +
$scope.data.email + '&realname=' +
$scope.data.firstname + ' ' +
$scope.data.lastname +
'&mailpassword=false&reason=Fun_and_profit&language=en&token=' + myToken).then(
function(response) {
alert("Registration successful ! You can log in now " + response.data.createaccount.username);
},
function(response) {
alert(response.data.error.info);
}); //End then
} //End register
$scope.signup = function() {
register(getToken);
} // End sign up
}); // End controller
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<ion-view ng-controller="registerController" title="Sign Up" view-title="Sign Up" name="login-view">
<ion-content class="padding">
<div class="list list-inset">
<label class="item item-input">
<input type="text" placeholder="Username" ng-model="data.username">
</label>
<label class="item item-input">
<input type="password" placeholder="Password" ng-model="data.password">
</label>
<label class="item item-input">
<input type="text" placeholder="Email" ng-model="data.email">
</label>
<label class="item item-input">
<input type="text" placeholder="First Name" ng-model="data.firstname">
</label>
<label class="item item-input">
<input type="text" placeholder="Last Name" ng-model="data.lastname">
</label>
<label class="item item-input">
<input type="text" placeholder="City" ng-model="data.city">
</label>
<label class="item item-input">
<input type="text" placeholder="Country" ng-model="data.country">
</label>
</div>
<button class="button button-block button-calm" ng-click="register(getToken())">Sign Up</button>
</ion-content>
</ion-view>
Anyone know how I can I do this ?
$httpcall is async, you will have to call second request inside success of first.