I've been googling this for hours...
here's my angularJS code:
var FrontControllers = angular.module('FrontControllers', [] );
FrontControllers.controller('LoginController', ['$scope', '$http', function($scope, $http){
$scope.user = {};
$scope.login = function() {
console.log($scope.user);
$http({
url: '/webapi/login',
method: 'POST',
data: $scope.user
}).success(function (data) {
alert("success!");
}).error(function(data) {
alert("failed =(");
});
};
}]);
here's the accompanying html
<div ng-controller="LoginController" id="login" class="box">
<form novalidate role="form" action="/webapi/login" id="loginForm">
<label for="signin" class="sr-only">Email or Username</label>
<input ng-model="user.username" type="text" autofocus class="form-control input-lg" id="username" name="username" size="20" placeholder="email or username">
<label for="password" class="sr-only">Password</label>
<input ng-model="user.password" type="password" class="form-control input-lg" id="password" name="password" size="10" placeholder="password">
<button ng-click="login()" type="submit" class="btn btn-lg btn-bright btn-block">Login</button>
</form>
</div>
No matter what I do, I end up with a POST request that gets cancelled. I've previously succeeded in logging in to /webapi/login with standard jQuery ajax code. The server is configured for AJAX, so there's no need for a urlencode header. The Payload looks correct, identical to the one that sent by jQuery ajax.
What might be the problem?
This is from Chrome developer/network:
Provisional headers are shown
Accept:application/json, text/plain, */*
Content-Type:application/json;charset=UTF-8
Origin:http://ec2-54-86-242-50.compute-1.amazonaws.com
Referer:http://ec2-54-86-242-50.compute-1.amazonaws.com/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.104 Safari/537.36
X-DevTools-Emulate-Network-Conditions-Client-Id:BB96CDC3-AD63-D024-E814-4726DF4843D8
Angular will not preventDefault() if the action parameter is set. See here
For this reason, Angular prevents the default action (form submission to the server) unless the element has an action attribute specified.
You should probably also use ng-submit="login() on the <form> instead of ng-click, so that it will submit the form when the user presses Enter
Try removing form's
action="/webapi/login"
and button's
type="submit"
Related
Im new to mobile development, especially using Ionic. Please help me out
I have this code for my route
.state('auth', {
url: '/auth',
templateUrl: 'templates/login.html',
controller: 'AuthCtrl'
I have this code for my login.html
<ion-view view-title="Login" name="login-view">
<ion-content class="padding">
<div class="list list-inset">
<label class="item item-input">
<input type="text" placeholder="Mobile Number" ng-model="mobile_number">
</label>
<label class="item item-input">
<input type="password" placeholder="Password" ng-model="password">
</label>
</div>
<button class="button button-block button-calm" ng-click="login()">Login</button>
</ion-content>
and for my AuthCtrl
.controller('AuthCtrl', function($scope,$auth,$state) {
$scope.login = function() {
var credentials = {
mobile_number : $scope.mobile_number,
password : $scope.password,
}
console.log(credentials);
$auth.login(credentials).then(function(data) {
// If login is successful, redirect to the users state
$state.go('tab.dash', {});
});
}
})
I always get this Object {mobile_number: undefined, password: undefined} when calling console.log(credentials)
I always put values in my forms, but its always undefined. Why?
First initialize your scope credentials model:
$scope.credentials = {
'mobile_number' : ''
'password' : '',
}
Then bind your inputs to the scope properties:
<input type="text" placeholder="Mobile Number" ng-model="credentials.mobile_number">
<input type="password" placeholder="Password" ng-model="credentials.password">
And make use of $scope.credentials that now has your form data:
$auth.login($scope.credentials).then(function(data) {
// If login is successful, redirect to the users state
$state.go('tab.dash', {});
});
Your credentials object is not bound to scope. It looks like You need to declare $scope.credentials outside of login. Also on the input, ngModel should bind to credentials.password and credentials.mobile_number.
Actually it works good for me, I did a little plunker to test it. I was facing similar problem cause I added ng-pattern and ng-minLength directive in the input. In this case you will get undefined unless the input value is valid pattern and length. To fix it I added property to your input element
<input type="tel" ng-model="credentials.mobile_number"
ng-model-options="{allowInvalid:true}"/>
I hope that helps , good luck
login.controller
angular
.module('app.pages.auth.login')
.controller('LoginController', LoginController);
/** #ngInject */
function LoginController($http, $location)
{
var vm = this;
vm.submitPost = function(userData){
$http({
url: 'http://localhost:7200/api/pages/auth/login',
method: 'POST',
data: userData
}).then(function(res) {
if(res.data.success){
$location.path('/pages/profile');
console.log(res.data.message);
//vm.message=res.data.message;
} else {
//console.log(res.data.message);
//vm.message=res.data.message;
$location.path('/pages/auth/login');
}
}, function(error) {
alert('here');
});
};
}
api.js
router.get('/pages/auth/login', function(req, res) {
console.log(req.flash('loginMessage'));
res.render('auth/login/login.html', { message: req.flash('loginMessage') });
});
router.get('/pages/profile', isLoggedIn, function(req, res) {
return res.json({
success:true,
//message: 'Login Success',
})
res.render('profile/profile.html', {user:req.user });
});
I am not getting any response from router to controller. It shows the alert message 'here'. Is there any thing wrong done here? please help me to fix this.
login.html
<form name="loginForm">
<div class="alertmessage" >{{vm.message}}</div>
<md-input-container flex md-no-float>
<input ng-model="vm.form.username" placeholder="Username" translate
translate-attr-placeholder="LOGIN.USERNAME" name="username" required="true">
<div ng-messages="loginForm.username.$error" ng-show="loginForm.username.$touched">
<div ng-message="required">This field is required</div>
</div>
</md-input-container>
<md-input-container flex md-no-float>
<input ng-model="vm.form.password" type="password" placeholder="Password" translate
translate-attr-placeholder="LOGIN.PASSWORD" name="password" required="true">
<div ng-messages="loginForm.password.$error" ng-show="loginForm.password.$touched">
<div ng-message="required">This field is required</div>
</div>
</md-input-container>
<div class="remember-forgot-password" layout="row" layout-sm="column"
layout-align="space-between center">
<md-checkbox class="remember-me" ng-model="data.cb1" aria-label="Remember Me">
<span translate="LOGIN.REMEMBER_ME">Remember Me</span>
</md-checkbox>
<a ui-sref="app.pages_auth_forgot-password" class="forgot-password md-accent-color"
translate="LOGIN.FORGOT_PASSWORD">Forgot Password?</a>
</div>
<md-button class="md-raised md-accent" aria-label="LOG IN" translate="LOGIN.LOG_IN"
translate-attr-aria-label="LOGIN.LOG_IN"
ng-click="vm.submitPost(vm.form);">
LOG IN
</md-button>
</form>
Please verify what is the value of 'userData' coming from the front end/from where u r calling it. Seems there is an issue with that only!
If thats not the issue then please check the network in developer tools that why your service is failing?
To go to network(on chrome) click F12 >> Network.
Verify your service call and see whats the issue!
EDIT:
where is your 'headers' in service call? You intentionally din't add or you missed it?
This is one more image of network tabWhen i click after login it showed like this
Network tab image showing like this
i'm approching angularJS and i'd like to submit a form to db via php.
i tried this but it does not work.
any help?
i get an error when i click the submit button.
thanks.
//index.html
angular.module("myApp")
.controller("addUtentiCtrl", function($scope, $http) {
$scope.utenteForm = {};
$scope.submit = function() {
$http({
method : 'POST',
url : 'backInsertUtenti',
data : param($scope.utenteForm),
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.success(function() {
alert("Dati inseriti correttamente!");
})
.error(function() {
alert("Errore inserimento dati!");
});
};
});
//aggiungiUtente.html
<form ng-submit="submit()" ng-controller="addUtentiCtrl" novalidate>
<input type="text" ng-model="utenteForm.nome" name="nome" ng-maxlength="10" ng-required="true">
<input type="text" ng-model="utenteForm.cognome" name="cognome" ng-maxlength="10" ng-required="true">
<input type="text" ng-model="utenteForm.citta" name="citta" ng-maxlength="10" ng-required="true">
<input ng-enable="utenteForm.$valid" type="submit" id="submit" value="Submit" />
</form>
//backInsertUtenti.php
<?php
//define of variable for the connection
$db= new mysqli($host,$username,$password,$db_name);
$sql=$db->prepare("INSERT INTO utenti (id, nome, cognome, citta) VALUES (0, ?, ?, ?)");
$sql->bind_param('sss',$_POST['nome'],$_POST['cognome'],$_POST['citta']);
$sql->execute();
?>
I'm trying to send a post form to a PHP script, and every time, the POST request shows as canceled.
My controller looks like this:
var authenticationControllers = angular.module('authenticationControllers', []);
authenticationControllers.controller('Authentication', ['$scope', '$http', function($scope, $http) {
$scope.WPlogin = function () {
var mydata ={
'action': 'ajaxlogin',
'username': $scope.user.username,
'password': $scope.user.password,
'security-login': pluginParams.nonce,
'_wp_http_referer': '/s/play/'
};
$http({
method: 'POST',
url: $scope.ajaxURL, //This is defined earlier, I'm sure this is valid
data: jQuery.param(mydata),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data, status, headers, config) {
console.log(data.message);
}).error(function(e){alert('error')});
};
}]);
And the form looks like this:
<div class="white-popup mfp-hide" id="login-modal" ng-controller="Authentication">
<form name="loginform" id="loginform" novalidate>
<h1>Login</h1>
<p class="status"></p>
<label for="username">Username</label>
<input id="username" type="text" name="username" ng-model="user.username" ng-required="true">
<label for="password">Password</label>
<input id="password" type="password" name="password" ng-model="user.password" ng-required="true">
<a class="lost" href="<?php echo wp_lostpassword_url(); ?>">Lost your password?</a>
<button class="submit_button" ng-disabled="loginform.$invalid" ng-click="WPlogin()" type="submit" name="submit"> Login</button>
</form>
</div>
Whenever I try to submit the form, the error alert pops up, but no console errors. Then, the page reloads, and I can see the form parameters in the URL (like a get request), and if I then submit my form (without deleting the get parameters), then the request is a success.
Can anyone tell me what I'm doing wrong?
Update
I added $event.preventDefault(); to the form (passing $event from the form), and now it all works as expected, but I don't understand, why do I need that? I thought AngularJS would automatically prevent the form submission.
We are using Spring 4 (Annotation based configuration) and AngularJS for building our application. In one of the usecase, we need to upload a document. On submitting the form, we need to send the form data (apart from file uploaded file, there are fields which are part of the form) and the file content as part of the POST request.
#Bean(name="multipartResolver")
public CommonsMultipartResolver multipartResolver(){
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
return multipartResolver;
}
The HTML form contents:
<form method="post" id="fromFileUpload"
enctype="multipart/form-data" ng-submit="create()">
<div class="form-group">
<label for="inputValue" class="col-md-offset-2 col-md-4 form-element">Input Value</label>
<div class="col-md-6 form-element">
<input class="form-control" ng-model="model.value"
name="val" required autofocus>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4 col-xs-12" for="file">Please
upload the file : <span class="required">*</span>
</label>
<div class="col-xs-4 input-max controls ">
<input class="inline-block" type="file" name="file"
ng-model="file" data-rule-required="true" id="file"
accept=".xls">
</div>
<span id="vaildFile" class="text-success icon-ok hide">Valid
File</span> <span id="invaildFile" class="text-error icon-remove hide">
Invalid File</span>
</div>
<div class="box-header">
<div class="actions">
<button type="submit" class="btn btn-primary">
<i class="icon-arrow-right"></i> Create
</button>
</div>
</div>
</form>
Below is the angularJS code :
$scope.create = function() {
var formData=new FormData();
formData.append("file",$scope.file);
formData.append("docData", angular.toJson($scope.model));
console.log(formData);
$http({
method: 'POST',
url: "http://localhost:8080/saprof/value",
headers: {'Content-Type': false},
data: formData,
transformRequest: function(data, headers) {
return data;
}
})
.success(function(data, status) {
alert("Success");
})
.error(function(data, status) {
alert("Error");
});
};
Below is the controller Code (Annotated with #RestController)
#RequestMapping(value="/saprof/value", method=RequestMethod.POST)
public void createValue(HttpServletRequest request, HttpServletResponse response, HttpSession session){
LOGGER.info("Request is of type MultiPartRequest "+(request instanceof MultipartHttpServletRequest)); // false
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
LOGGER.info("isMultiPart Request : "+isMultipart); // false
}
Problem:
I am getting RequestFacade object as the request object and not MultiPartServletRequest. Hence i am not able to retrieve the form data + file contents from this request.
When see the request which is been sent using browser, below is the content:
Request Payload
------WebKitFormBoundaryzfZtWVlK6xH8aSyf
Content-Disposition: form-data; name="file"
[object Object]
------WebKitFormBoundaryzfZtWVlK6xH8aSyf
Content-Disposition: form-data; name="docData"
{"value":"test"}
------WebKitFormBoundaryzfZtWVlK6xH8aSyf--
Need your help in correcting my mistakes. Let me know if you need any further details. Really appreciate your help.
Regards,
Manjunath
I used this module on my own project and it worked like a charm:
danialfarid/ng-file-upload