angularjs $http.post with parameters get null - angularjs

I am using angular for login page but return null parameters to controller.
view page:this my code in view page
<div ng-controller="LoginController">
<form novalidate name="f1" ng-submit="Login()">
<div style="color:rgb(142,2,2)">{{Message}}</div>
<table ng-show="!IsLogedIn">
<!-- Here ng-show="!IsLogedIn" means I want to hide table after loged in-->
<tr>
<td>Username : </td>
<td>
<!-- Here ng-class="Submitted?'ng-dirty':''" Means if submitted (clicked submit button) then make this dirty state
for show red border-->
<input type="text" ng-model="Login.Username" name="cUsername" ng-class="Submitted?'ng-dirty':''" required autofocus />
<span class="error" ng-show="(f1.cUsername.$dirty || Submitted) && f1.cUsername.$error.required">Username required</span>
<!-- ng-show="(f1.cUsername.$dirty || Submitted) && f1.cUsername.$error.required" Means I want to show this span only when
the control cUsername is invalid-->
</td>
</tr>
<tr>
<td>Password : </td>
<td>
<input type="password" ng-model="Login.pass" name="cPassword" ng-class="Submitted?'ng-dirty':''" required autofocus />
<span class="error" ng-show="(f1.cPassword.$dirty || Submitted) && f1.cPassword.$error.required">Password required</span>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="Login" />
</td>
</tr>
</table>
</form>
</div>
i need to use the returned value from this factory in other factories.
but get null parametrs
mycontroll.js
angular.module('MyApp')
.controller('LoginController', function ($scope, LoginService) {
$scope.IsLogedIn = false;
$scope.Message = '';
$scope.Submitted = false;
$scope.IsFormValid = false;
$scope.LoginData = {
Username: '',
Password: ''
};
//Check is Form Valid or Not // Here f1 is our form Name
$scope.$watch('f1.$valid', function (newVal) {
$scope.IsFormValid = newVal;
});
$scope.Login = function () {
$scope.Submitted = true;
if ($scope.IsFormValid) {
LoginService.GetUser($scope.LoginData).then(function (d) {
if (d.data.Username != null) {
$scope.IsLogedIn = true;
$scope.Message = "Successfully login done. Welcome " + d.data.Name;
}
else {
alert('Invalid Credential!');
}
});
}
};
})
.factory('LoginService', function ($http) {
var fac = {};
fac.GetUser = function (d) {
return $http({
url: '/login/Login',
method: 'POST',
data: JSON.stringify(d),
headers: { 'content-type': 'application/json' }
});
};
return fac;
});
logincontrol
[HttpPost]
public virtual JsonResult Login(Login d)
{
using (CrudAngularEntities dc = new CrudAngularEntities())
{
var user = dc.Users.Where(a => a.Username.Equals(d.Username) && a.pass.Equals(d.pass)).FirstOrDefault();
return new JsonResult { Data = user, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
}

You are passing $scope.LoginData to the function LoginService.GetUser. The corresponding server model is Login. Hence its signature needs to be same.
$scope.LoginData = {
pass : '',
Username: ''
};
Then you mapped the ng-models to something else (to Login obj). You may need to replace inputs for username and password with
<input type="text" ng-model="LoginData.Username"
<input type="password" ng-model="LoginData.pass"

Related

AngularJS - inputs in a html-table inside a form

It works now...
I GET array and stick name in input, then I change name in input and PUT it.
HTML
<form id="edit">
<table>
<tr>
<th>Name: </th>
<td>
<input id="name" form="edit" type="text" ng-model="name" required>
</td>
</tr>
</table>
<button ng-click="edit()">Submit</button>
</form>
AngularJS
$scope.display = function()
{
var connection = $http(
{
method: 'GET',
url: 'http://localhost:8080/students?id=' + $scope.id
})
.then(function(response)
{
$scope.myArray = response.data;
$scope.name = $scope.myArray[0].name;
})
You need to check the status_code on the response not on response.data:
if (response.status == 200)
{
success();
}
else
{
fail();
}
You should check your $scope.name properly update in controller when you hit the button. your request might be fail because of your $scope.name not update in controller properly.

Angular contact form - undefined field after after sending

Here is my index.html
<div data-ng-controller="help">
<div id="messages" class="alert alert-success" data-ng-show="messages" data-ng-bind="messages"></div>
<div data-ng-show="progress.active()" style="color: red; font-size: 50px;">Sending…</div>
<form name="helpForm" novalidate role="form">
<div class="form-group">
<label for="name">Your Name </label>
<span class="label label-danger" data-ng-show="submitted && helpForm.name.$error.required">Required!</span>
<input type="text" name="name" data-ng-model="userName" class="form-control" required />
</div>
<div class="form-group">
<label for="email">Your E-mail address</label>
<span class="label label-danger" data-ng-show="submitted && helpForm.email.$error.required">Required!</span>
<span class="label label-danger" data-ng-show="submitted && helpForm.$error.email">Invalid email!</span>
<input type="email" name="email" data-ng-model="userEmail" class="form-control" required />
</div>
<div class="form-group">
<label for="message">Message</label>
<span class="label label-danger" data-ng-show="submitted && helpForm.message.$error.required">Required!</span>
<textarea name="message" data-ng-model="userMessage" class="form-control" required></textarea>
</div>
<button data-ng-disabled="progress.active()" data-ng-click="submit(helpForm)" class="btn btn-default">Submit</button>
</form>
And part of my app.js
angular.module('myApp', ['ajoslin.promise-tracker'])
.controller('help', function ($scope, $http, $log, promiseTracker, $timeout) {
$scope.subjectListOptions = {
'bug': 'Report a Bug',
'account': 'Account Problems',
'mobile': 'Mobile',
'user': 'Report a Malicious User',
'other': 'Other'
};
$scope.progress = promiseTracker();
$scope.submit = function(form) {
$scope.submitted = true;
if (form.$invalid) {
return;
}
var $promise = $http({
method: 'POST',
url:'api/contactUs',
params: {
'callback' : 'JSON_CALLBACK',
'userName' : $scope.userName,
'userEmail' : $scope.userEmail,
'userMessage' : $scope.userMessage
}
})
.success(function(data, status, headers) {
if (data.status == 'OK') {
$scope.userName = null;
$scope.userEmail = null;
$scope.userMessage = null;
$scope.messages = 'Your form has been sent!';
$scope.submitted = false;
} else {
$scope.messages = 'Oops, we received your request, but there was an error processing it.';
$log.error(data);
}
})
.error(function(data, status, headers) {
$scope.progress = data;
$scope.messages = 'There was a network error. Try again later.';
$log.error(data);
})
.finally(function() {
$timeout(function() {
$scope.messages = null;
}, 9000);
});
After sending the letter to mail, all fields (name, email, message) in the form are displayed as "Undefined"
I use an node.js server and connect via api (api/contactUs)
I can not understand what the problem is, already tried everything I could, but the error remains.
Please help with the solution of this problem.
Thank you in advance!
When you use POST method, you should pass data object instead of params object.
Change this:
params: {
'callback' : 'JSON_CALLBACK',
'userName' : $scope.userName,
'userEmail' : $scope.userEmail,
'userMessage' : $scope.userMessage
}
To this:
data: {
'callback' : 'JSON_CALLBACK',
'userName' : $scope.userName,
'userEmail' : $scope.userEmail,
'userMessage' : $scope.userMessage
}

Angular js:Not able to get the response for the rest method

I am trying to create a simple login form using angular js and rest webservice.
I am able to call the rest webservice, but not able to get the response.
1)Login form:
<div class="col-md-6 col-md-offset-3">
<h2>Login</h2>
<div class="alert alert-danger">Error</div>
<form name="form" role="form" method="post" data-ng-submit="login(credentials)"
data-ng-controller="LoginController">
<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username" id="username" class="form-control" data-ng-model="credentials.username" required />
<span class="help-block">Username is required</span>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" id="password" class="form-control" data-ng-model="credentials.password" required />
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Login</button>
<img src="img/ajax-loader-blue.gif" />
Register
</div>
</form>
</div>
2)Restwebservice
#Path("/login")
public class LoginRestfulService {
#POST
#Consumes(MediaType.APPLICATION_JSON)
public Users getUserProfile(CredentialInBean credentials) {
System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"+" credentials: "+credentials.getUsername()+""+credentials.getPassword());
UserService userService = new UserService();
return userService.getUserProfile(credentials);
}
}
3)
public Users getUserProfile(CredentialInBean credentials) {
if(credentials!=null && credentials.getUsername().equals("Firstname")){
Users user = new Users();
user.setFirstName("Firstname");
user.setLastName("lastname");
return user;
}
return null;
}
4)LoginController
app.controller('LoginController', function($scope, $rootScope, AUTH_EVENTS,
AuthService) {
$scope.credentials = {
username : '',
password : ''
};
$scope.login = function(credentials) {
AuthService.login(credentials).then(function(user) {
$rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
$scope.currentUser = null;
$scope.setCurrentUser = function(user) {
$scope.currentUser = user;
};
}, function() {
$rootScope.$broadcast(AUTH_EVENTS.loginFailed);
});
};
})
5)AuthService
services.factory('AuthService', function($http, Session) {
var authService = {};
var response='';
authService.login = function(credentials) {
return $http.post('/aclf/rest/login', credentials).then(function(response) {
if (response !== null) {
response = { success: true };
} else {
response = { success: false, message: 'Username or password is incorrect' };
}
alert(response.data);
return response.data;
});
};
});
Here respose.data comes as undefined.
Can any one help me to solve the issue?
you can't override the response here.
For the best you can add more attributes to this object like:
services.factory('AuthService', function($http, Session) {
var authService = {};
var response='';
authService.login = function(credentials) {
return $http.post('/aclf/rest/login', credentials).then(function(response) {
if (response !== null) {
response.success = true ;
} else {
response = {};
response.success = false;
response.message = 'Username or password is incorrect';
}
alert(response.data);//you will preserve the data
return response.data;//won't be undefined
});
};
});

AngularJs and Controller alias

I tried to alias the AngularJS controller in the view, but for some strange reason - it does not seem to respond when I prefix the methods and properties - any idea what might be causing it?
Here's my view (I'm using it with Laravel 5.1):
#extends('admin.template.layout-login')
#section('content')
<div class="row">
<div class="large-6 medium-8 columns large-offset-3 medium-offset-2" ng-controller="LoginController as login">
<form
name="htmlForm"
class="panel hide"
ng-submit="login.submit()"
ng-class="{ 'show-block' : !login.isRequestCompleted() }"
novalidate
>
<label for="username">
Username: *
<ng-messages
for="htmlForm.username.$error"
class="hide"
ng-class="{ 'show-inline' : login.isSubmitted() }"
>
<ng-message
when="required"
class="warning"
>Please provide your email address</ng-message>
<ng-message
when="email"
class="warning"
>Invalid email address</ng-message>
<ng-message
when="unsuccessful"
class="warning"
>Incorrect login details</ng-message>
<ng-message
when="suspended"
class="warning"
>Your account has been suspended</ng-message>
</ng-messages>
</label>
<input
type="email"
ng-model="formData.username"
name="username"
id="username"
required
>
<label for="password">
Password: *
<ng-messages
for="htmlForm.password.$error"
class="hide"
ng-class="{ 'show-inline' : login.isSubmitted() }"
>
<ng-message
when="required"
class="warning"
>Please provide your password</ng-message>
<ng-message
when="password"
class="warning"
>Invalid password</ng-message>
</ng-messages>
</label>
<input
type="password"
ng-model="formData.password"
name="password"
id="password"
required
password
>
<label for="remember">
<input
type="checkbox"
ng-model="formData.remember"
name="remember"
id="remember"
> Remember Me
</label>
<input
type="submit"
class="small button"
value="SEND ENQUIRY"
ng-if="!login.isOutForDelivery()"
>
<button
type="button"
class="small button"
disabled
ng-if="login.isOutForDelivery()"
>
PLEASE WAIT <i class="fa fa-spinner fa-spin"></i>
</button>
</form>
<div
class="hide"
ng-class="{ 'show-block' : login.isRequestCompleted() }"
ng-bind-html="login.trustAsHtml(confirmation)"
></div>
</div>
</div>
#endsection
and here's the AngularJS controller module:
(function(window, angular, app) {
"use strict";
app.controller(
'LoginController',
[
'$scope',
'$controller',
'$window',
function(
$scope,
$controller,
$window
) {
angular.extend(this, $controller('FormController', { $scope: $scope }));
$scope.submit = function() {
if ( ! $scope.isValid()) return false;
$scope.data = {
username : $scope.formData.username,
password : $scope.formData.password
};
$scope.submitRequest(
'/admin',
$scope.data
)
.success(function(data, status, headers, config, statusText) {
$window.location.href = data.url;
})
.error(function(data, status, headers, config, statusText) {
$scope.validation(data);
$scope.endOutForDelivery();
return false;
});
};
}
]
);
})(window, window.angular, window.CmdSystem.App);
Plus the FormController that the previous extends:
(function(window, angular, app) {
"use strict";
app.controller(
'FormController',
[
'$scope',
'RequestService',
'ContentService',
function(
$scope,
RequestService,
ContentService
) {
$scope.outForDelivery = false;
$scope.requestCompleted = false;
$scope.submitRequest = function(url, formData) {
$scope.outForDelivery = true;
return RequestService.post(url, formData);
};
$scope.responseReceived = function() {
$scope.requestCompleted = true;
$scope.outForDelivery = false;
};
$scope.isResponseReceived = function() {
return $scope.requestCompleted && ! $scope.outForDelivery;
};
$scope.endOutForDelivery = function() {
$scope.outForDelivery = false;
};
$scope.trustAsHtml = ContentService.trustAsHtml;
$scope.isValid = function() {
return $scope.htmlForm.$valid;
};
$scope.isSubmitted = function() {
return $scope.htmlForm.$submitted &&
! $scope.isRequestCompleted();
};
$scope.isRequestCompleted = function() {
return $scope.requestCompleted;
};
$scope.isOutForDelivery = function() {
return $scope.outForDelivery;
};
$scope.validation = function(data) {
angular.forEach(data, function(value, key) {
this[key].$error[value] = true;
}, $scope.htmlForm);
};
}
]
);
})(window, window.angular, window.CmdSystem.App);
None of the methods are on the controller. They're all defined on the $scope. So you can't access them using the login alias, which refers to the controller, not to the scope.
If you want to be able to call
login.foo()
from the view, then the method must be set on the controller, not on the scope:
this.foo = function() { ... };

how to send values from view controls to angularjs controller..?

In my Angularjs MVC application i write code for lo-gin which accept values from two text boxes as user name & password
my Angularjs controller code is as which works fine but problem with view
$scope.Login = function Login(U_Name, U_PWD) {
//Defining the $http service for login the admin user
$http({
method: 'POST',
url: '/Admin/IsAuthenticate',
data: { User_Name: U_Name,
User_PWD: U_PWD }
}).success(function (result) {
if (result == true) {
alert('user is valid');
}
else {
alert('unauthorised access!');
}
})
.error(function (error) {
//Showing error message
$scope.status = 'Unable to connect' + error.message;
});
}
this code is executing on ng-click event but doesn't accept values from input boxes
my view code is as:
<div ng-app="angApp">
<div ng-controller="AdminCtrl">
<div class="admin-login">
<h2>using angularjs</h2>
<input type="text" id="txtUserAng" placeholder="User Name" ng-model="U_Name" />
<input type="password" id="txtPWDAng" placeholder="Password" ng-model="U_PWD" />
<input type="button" id="login" value="login" ng-click="Login()" />
</div>
</div>
</div>
Your problem is that you are not passing U_Name, U_PWD variable to Login function. You need to pass input values to your function.
There are 2 ways of achieving it.
First, Pass the model directly to function like
<input type="button" id="login" value="login" ng-click="Login(U_Name, U_PWD)" />
Second, Use $scope.U_Name and $scope.U_PWD
$scope.Login = function() {
var U_Name = $scope.U_Name,
U_PWD = $scope.U_PWD
}
In controller get this
this example without set login parametr
$scope.Login = function Login() {
var U_Name = $scope.U_Name;
var U_PWD = $scope.U_PWD;
console.log($scope.U_Name);
console.log($scope.U_PWD);
}
And you can set login function parrameters that model
<input type="button" id="login" value="login" ng-click="Login(U_Name, U_PWD)" />
use this
data:
{
User_Name: $scope.U_Name,
User_PWD: $scope.U_PWD
}

Resources