Submit login with AngularJS - angularjs

I want to avoid using <form> so instead of
<form action="./login" method="post">
<input type="text" placeholder="Username" name="username">
<input type="password" placeholder="Password" name="password">
<input type="submit" value="Login">
</form>
I want to use something like
<input type="text" placeholder="Nombre de usuario" data-ng-model="username">
<input type="password" placeholder="ContraseƱa" data-ng-model="password">
<a data-ng-click="doLogin()">Login</a>
And in controller:
$scope.doLogin=function(){
var url = '/login?username=' + $scope.username + '&password=' + $scope.password;
$http.post(url).then(function(msg){
console.log(msg);
});
}
The request is sent to Spring framework and work perfectly when I use form,but when I use Angular to perform same action it gives me an error POST http://localhost:8080/login?username=admin&password=admin 404 (Not Found)
What changes I have to do? I would like to have the perfectly the same functionality of submit, as on wrong credentials Spring framework redirects me on another view.

I think that you should not delete the form but change it to a pure angularjs form with a ngSubmit attribute (be sure to delete the action attribute).
Like this :
<form method="post" ng-submit="doLogin()">
<input type="text" placeholder="Username" name="username">
<input type="password" placeholder="Password" name="password">
<input type="submit" value="Login">
</form>
Then, in your js controller, your http call is a post call with parameters passed like a get call (param1=value1&param2=...), change your call to pass login parameters in post.
$scope.doLogin=function(){
var url = '/login';
$http.post(url, {username: $scope.username, password: $scope.password}).then(function(msg){
console.log(msg);
});
}
This way, your angularjs form will behave the same way than your previous code.

Related

Creating User model? form.is_valid always returning false

Trying to add new User (using Django default User model).
#api/views.py
#csrf_exempt
#api_view(['GET', 'POST', ])
def signup(request):
print(request.POST)
if request.method == 'POST':
form = UserCreationForm(data=request.POST)
if form.is_valid():
form.save()
return Response('created new user')
else:
return Response('did not')
Here is the form. I am not using raw html, it is a React component
<form className="register-form" noValidate action="api/register/"
method="post" autoComplete="off">
<input type="text" name="username"></input>
<input type="password" name="password"></input>
<input type="submit" value="Submit"></input>
</form>
clicking submit successfully sends a post request to api/register, which in urls.py points it to views.signup.
form.is_valid is always evaluating to false, so the User isn't getting created. As far as I can tell, the only required fields to create the User are username and password. I have also tried removing the label "data" in UserCreationForm(data=request.POST). This doesn't work either. Where am I going wrong?
Solved by printing to console and checking errors in signup function
print(request.POST)
print(form.errors)
print(form.non_field_errors)
User model actually requires username, password1, and password 2. Changed form to
<form className="register-form" noValidate action="api/register/"
method="post" autoComplete="off">
<input type="text" name="username"></input>
<input type="password" name="password1"></input>
<input type="password" name="password2"></input>
<input type="submit" value="Submit"></input>
</form>
which solved the issue

Using ng-token-auth submitLogin method to a different url

I am using ng-token-auth with angular/ionic that connects to a rails api. I am currently working on the login page. I have the following form in the code:
<form ng-submit="submitLogin(loginForm)" role="form" ng-init="loginForm = {}">
<input type="email"
name="email"
id="email"
placeholder="Email"
ng-model="loginForm.email"
required="required" />
<input type="password"
name="password"
id="password"
placeholder="Password"
ng-model="loginForm.password"
required="required" />
<button type="submit" class="button button-block button-positive">Sign in</button>
</form>
The submitLogin function succesfully sends a post request to:
POST http://localhost:8100/api/auth/sign_in
The problem is that this is on the ionic server. The rails app is located at localhost:3000. How do I get the post request to go to that URL. Since almost every single angular api ever created will be sending requests to a different server, I have to imagine this is included somehow.
You have to change default apiUrl in your app.js file (or whatever you called it) using .config
angular.module('myApp', ['ng-token-auth'])
.config(function($authProvider) {
$authProvider.configure({
apiUrl: 'http://localhost:3000'
});
});
Here is the link to all possible configuration options for
ng-token-auth

Error with binding text input

i have this strange thing that happens in my application every time it starts, but first the code
HTML
<form ng-submit="login()" class="login">
<input type="text" ng-model="data.username" placeholder="username" value="username" class="form-control" popover="inserisci qui il tuo username" popover-trigger="focus" popover-placement="right"></input><br>
<input type="password" ng-model="data.password" placeholder="password" value="password" class="form-control" popover="inserisci qua la tua password" popover-trigger="focus" popover-placement="right"><br>
<input class="btn-primary btn-lg" type="submit" value="Login">
JS
var loginCtrl=function($scope,$http,$modalInstance,$state){
$scope.data = {username : '',password:''};
var data=$scope.data;
$scope.login=function(){
$http.post(server[0]+someurl,{name:data.username,password:data.password})
.then(function (response) {
var status=response.status;
loggedOk=true;
$state.go('home',{username:data.username,logged:status});
$modalInstance.close();
},
function(response){
var status=response.status;
alert(status);
logged=false;});
};
this is clearly a little login app. My problem is that when i start the app and the text area is all ready filled with a user and a password saved before, if i press login, the post request send empty params.
Strangely if i delete a letter from the two params and i rewrite it everything goes ok, any idea why?
I think your main issue is that your bindings are not to your data object. Change ng-model="username" to ng-model="data.username", and do the same for password. That should make everything bound up correctly for login.

Clearing all inputs and restoring .ng-pristine on click

It's still the first day of me using AngularJS after inheriting the project from a fellow developer. I was wondering, I have a login/registration form on my interface that is hidden once the items/form is submitted. Now once the user has submitted is there a correct or proper way to clear the form of it's entries and restore the .ng-pristine class on the items. The reason for this is should the user choose to log out and then login again (or another user wishes to register) the form is populated and has the validation css applied to it already. I don't want this, I would want everything to be empty and no CSS applied.
I can do this in JavaScript (obviously) however with AngularJS being a different approach I was wondering if I should approach this issue another way rather than loop through the form items and append a class to each item whilst clearing it's value.
This an example of one of my forms
<form name="signupForm" novalidate ng-submit="register(user)">
<div><label for="email">email:</label><input type="email" id="email" name="email" required ng-model="user.email" ng-minlength=4></div>
<div><label for="userName">Username:</label><input type="text" name="userName" id="userName" ng-model="user.userName" required ng-pattern="/^[A-Za-z0-9 \-_.]*$/" ng-minlength=4></div>
<div><label for="firstName">Vorname:</label><input type="text" name="firstName" id="firstName" ng-model="user.firstName" required ng-pattern="/^[A-Za-z \-_.]*$/" ng-minlength=3></div>
<div><label for="lastName">Nachname:</label><input type="text" name="lastName" id="lastName" ng-model="user.lastName" required ng-pattern="/^[A-Za-z \-_.]*$/" ng-minlength=4></div>
<div><label for="password1">Passwort:</label><input type="password" name="password1" id="password1" ng-model="user.password1" required ng-minlength=4></div>
<div><label for="password2">Passwort wiederholen:</label><input type="password" name="password2" id="password2" ng-model="user.password2" valid-password2 ng-minlength=4 pw-check="password1"></div>
... and so on
Many thanks
The form will appear in the correct scope under its name, i.e. $scope.signupForm. Additionally the object populating the form is $scope.user. In your controller, do:
$scope.user = {}; // or new User() if it is your case
$scope.signupForm.$setPristine();
In case $scope.signupForm is undefined, put a controller directly on the form, and place the code above (and anything else applicable) inside this new controller:
<form name="signupForm" novalidate ng-submit="register(user)"
ng-controller="NewCtrl">
(This may happen due to scope nesting under your original controller.)
Just refer to this post :
Reset form to pristine state (AngularJS 1.0.x)
In the main question you got reference to issues and pull request on AngularJS. In resume you have to use $setPristine() method to your form.
Hope it helps !
var app = angular.module('App', []);
app.controller('formController', function($scope, $document){
$scope.Clear = function(){
angular.forEach(angular.element($document[0].querySelectorAll('input[type=text], input[type=email], input[type=password]')), function (elem, index) {
elem.value = '';
/*
Just extra do something
elem.parent().parent().removeClass('has-error has-success');
elem.parent().parent().children().find('span').removeClass('glyphicon-exclamation-sign glyphicon-ok');
*/
});
$scope.myForm.$setPristine();
}
});
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
</head>
<body ng-app="App">
<div ng-controller="formController">
<form name="myForm">
<input type="text" name="FirstName" ng-model="FN"/> <br>
<input type="text" name="LastName"/>
<br>
<input type="text" name="UserName"/>
<br>
<input type="password" name="Password"/>
</form>
<button ng-click="Clear()">Clear</button>
</div>
</body>
</html>
Here is my Example, it worked for me i am using angularjs 1.6

roundcubelogin with window.open function

I have already done autologin to roundcube via the following script
<form name="webmail" action="http://localhost/roundcube_mail/" method="post">
<div class="info" style="color:#f00;display:none"></div>
<input name="_action" id="_action"value="login" type="hidden" />
<input name="_timezone" id="_timezone" value="_default_" type="hidden" />
<input name="ajax" id="ajax" value="1" type="hidden" />
User <input name="_user" id="_user" type="text" value="anupam#excoflare.com"/><br>
Pass <input name="_pass" id="_pass"type="password" value="anupam123"/><br>
<input type="submit" >
</form>
it will work correctly.But i want to auto login roundcubemail via java script with window.open method for my p
The problem is that you want do do a POST request instead of a GET request. This might help you:
JavaScript post request like a form submit

Resources