I am trying to create a new user in Angular. I'm attempting to send a POST request to my api through the client side to create a new user. Unfortunately I can't successfully send the post request. Sending the request through Postman is successful, but not through Angular. Any ideas on what could be the issue? Any help is appreciated.
userCtrl.js
//./public/app/controllers/userCtrl.js
angular.module('userCtrl',['userService'])
//SIGN UP CTRL ================================
//inject the User factory
.controller('userCreateController', function($location, User){
var vm = this;
//Function that creates a new user
vm.saveUser = function(){
//For spinner animation when signing up
vm.processing = true;
//Use the create funciton in the userService
User.create(vm.userData)
.then(function(data){
if(data.success){
$location.path('/login');
}else {
console.log('error');
vm.processing = false;
}
})
}//End saveUser
})//End userCreateController
userService.js
//userService.js
angular.module('userService', [])
.factory('User', function($http){
//create a user factory object
var userFactory = {};
//get a single user
userFactory.get = function(id){
return $http.get('/api/users/' + id);
};
//get all users
userFactory.all = function(){
return $http.get('/api/users/');
};
//create a user
userFactory.create = function(userData){
return $http.post('/api/users/', userData);
};
//update a user
userFactory.update = function(id, userData){
return $http.put('/api/users/' + id, userData);
};
//delete a user
userFactory.delete = function(id){
return $http.delete('/api/users' + id);
};
//return userFactory object
return userFactory;
});
routes.js
//./public/app/routes.js
angular.module('appRoutes', ['ngRoute'])
.config(function($routeProvider, $locationProvider){
$routeProvider
//homepage route
.when('/',{
templateUrl : 'app/views/pages/home.html'
})
.when('/login',{
templateUrl: 'app/views/pages/login.html',
controller: 'mainController',
controllerAs: 'login'
})
.when('/signup',{
templateUrl: 'app/views/pages/signup.html',
controller: 'userCreateController',
controllerAs: 'signup'
})
//Remove hash in the Url
$locationProvider.html5Mode(true);
})//End config
signup.html
<div class="row col-sm-6 col-sm-offset-3">
<div class="jumbtron">
<h1>Sign Up</h1>
<!-- Sign Up Form -->
<form ng-submit='signup.saveUser()'>
<!-- Name Input -->
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" placeholder="Enter Your Name" ng-model='signup.userData.name'>
</div>
<!-- Username Input -->
<div class="form-group">
<label>Username</label>
<input type="text" class="form-control" placeholder="Enter Username" ng-model='signup.userData.username'>
</div>
<!-- Password Input -->
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" placeholder="Enter Password" ng-model='signup.userData.password'>
</div>
<!-- Signup Button -->
<button type="submit" class="btn btn-block btn-success">
<!-- Show SignUP -->
<span ng-if="!signup.processing">Sign Up</span>
<!-- Show spinner animation when signing up -->
<span ng-if="signup.processing" class="spinner">
<span class="glyphicon glyphicon-repeat"></span>
</span>
</button>
</form>
<!-- End Sign Up Form -->
</div>
</div>
It is difficult to say without more information like the browser console log, but if you are minifying the code, it could be due to the implicit annotation syntax used in the controller injection.
Try to write it with the preferred Inline Array Annotation like:
.controller('userCreateController',
['$location', 'User', function($location, User){
...
}]);
at signup.html you are modifying signup.userData.* but at userCtrl.js you are sending vm.userData instead of $scope.signup.userData.
The problem could be that you are sending an undefined object instead of the userData object.
Related
I just began to study angular, tried to make some kind of SPA, but faced with problem of editing data in it. The obect is visible in console, but it hasn't appear on page, what I did wrong?
Here my controller:
var app = angular.module("testModule", ['ngRoute']);
app.config(function ($routeProvider){
$routeProvider.when('/', {
templateUrl: 'pages/main.html',
controller: 'addCtrl'
})
.when('/save', {
templateUrl: 'pages/save.html',
controller: 'editCtrl'
})
.when('/edit', {
templateUrl: 'pages/edit.html',
controller: 'addCtrl'
})
})
app.service('dataService', function($http) {
var data = {};
data.list = [];
var getData = function() {
$http.get("model/data.json").then(function (response) {
data.list = response.data;
});
}
return {
getDataFromJson: getData,
getData: data,
}
});
app.controller("mainCtrl", function($scope, dataService) {
dataService.getDataFromJson();
});
app.controller("editCtrl", function($scope, dataService) {
$scope.data = dataService.getData;
$scope.editData = function(adverse){
$scope.adverse= adverse;
console.log($scope.adverse)
}
});
and the part of page:
<div class="panel">
<form name="addForm" >
<div class="well" >
<div class="form-group">
<label for="name">Name:</label>
<input type='text' id="name" class="form-control" ng-model="adverse.name" placeholder={{adverse.name}} />
<label for="shop">Shop:</label>
<input type='text' id="shop" class="form-control" ng-model="adverse.shop" placeholder="{{adverse.shop}}" />
<label for="begin">Begin:</label>
<input id="begin" class="form-control" ng-model="adverse.begin" placeholder="{{adverse.begin}}" >
<label for="end">End:</label>
<input id="end" class="form-control" ng-model="adverse.end" placeholder="{{adverse.end}}" />
<button type="submit" class="btn btn-primary btn-block add_btn" ng-click="editData(adverse)">
Edit
</button>
</div>
</div>
</form>
</div>
Also here is a screenshot: the props of object suppose to be in the inputs but it hasn't.
enter image description here
If possible can you give me an example how I can do it by another way?
Recreated your scenario in this plunker. But it works. Please have a look at this plunker where you alo can see the StateProvider which is used instead of NgRoute
One thing I see which is incorrect is that you are sending the adverse object in the function and then setting the param to the scope adverse.
The thing is that the $scope.adverse already holds the values so you don't need to pass the value and setting it to the scope again. Remeber the scope is your glue between the view and ctrl
$scope.editData = function(){
console.log($scope.adverse)
}
I am currently trying to create a user login page where the user information is stored on a json file. I have created my GET method to the file but I cannot seem to redirect after the user has logged in successfully. Can you help me out?
I know that user login and validation done on the client side is A BAD IDEA but that is how I want to do it, without using a database.
Here is my HTML code:
<body ng-controller="myCtrl">
<form id="login-form">
<h3>User Login</h3>
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" id="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd">
</div>
<button type="submit" class="btn btn-default" id="login-button" ng-click="LogOn()">Login</button>
</form>
</body>
My JavaScript code:
var app = angular.module('myApp', [ ]);
app.controller("myCtrl",['$scope', '$http', function($scope, $http){
$scope.LogOn = function(){
$http.get('data.json').then(function(data){
$scope.users = data;
});
if (data.email == email) && (data.password = password{
window.location.href = 'www.google.com';
}
};
}]);
My JSON File:
[
{
"email":"something#yahoo.com",
"Password":"password"
},
{
"email":"test#yahoo.com",
"password":"test999"
},
{
"email":"xxx#mail.xx",
"password":"xxx"
}
]
Please try to open the link and check and run the code which is deployed in w3 schools
https://www.w3schools.com/code/tryit.asp?filename=FDVZY3NXVYG6
Put redirection code inside then
$http.get('data.json').then(function(data){
$scope.users = data;
if (data.email == email && data.password == password) {
window.location.href = 'www.google.com';
}
});
Obviously the if bellow has to be inside the .then( callback
if (data.email == email && data.password == password) {
window.location.href = 'www.google.com';
}
I have very big problem with login panel. I am still learning AngularJS.
Can you help me with login panel? Here is my code guys. I don't know what I should do now:
api.php:
public function getLogin()
{
$sql = "SELECT login FROM users WHERE login='$username' AND password='$password'";
return $this->db->fetchAll();
}
$app->get('/login', function () use ($app, $DataProvider) {
$login = $DataProvider->getLogin();
return $app->json($login);
});
login.html:
<div class="row">
<div class="col-lg-10 col-sm-10 col-xs-12">
<div class="flat-panel">
<div class="flat-panel-header">
<h3 class="flat-panel-heading">Panel logowania</h3>
</div>
<div class="flat-panel-body">
<div class="form-group">
<input type="text" class="form-control" ng-model="loginInfo.username" placeholder="Podaj login">
</div>
<div class="form-group">
<input type="password" class="form-control" ng-model="loginInfo.password" placeholder="Podaj hasło">
</div>
<div class="form-group">
<button ng-click="loginUser()" class="btn btn-primary">Zaloguj</button>
</div>
</div>
</div>
</div>
</div>
services.js:
app.factory('login', ['$http', function($http){
var _getLogin = function (callback) {
callback = callback||function(){};
$http.get('/api.php/login')
.success(function (data) {
callback(data);
});
};
return {
getLogin: _getLogin
};
app.js:
app.controller("LoginController", function($scope, $http){
$scope.loginInfo = {
username: undefined,
password: undefined
}
$scope.loginUser = function(){
var data = {
username: $scope.loginInfo.username,
password: $scope.loginInfo.password
}
};
})
For angular you need token based authentication.
What is token based authentication?
I never use silex but I found this
https://gonzalo123.com/2014/05/05/token-based-authentication-with-silex-applications/
Another method is normal login form and when user login in see angular app, but this is bad when you try create mobile app.
Take a look at for example this:
https://scotch.io/tutorials/token-based-authentication-for-angularjs-and-laravel-apps
I recommend jwt auth it's very nice!
I have my database with Firebase and now I'm trying to do a newsletter subscription, but I want to save the subscribers in Mailchimp and Firebase.
Mailchimp connection works perfectly, but I don't know how to integrate the Firebase connection in the same js.
This is what I have in the <head> tag
<script type="text/javascript">
angular.module("productLaunch", ["mailchimp"])
</script>
This in the <body> tag
<body ng-app="productLaunch"><section class="container-fluid subscribe" ng-controller="MailchimpSubscriptionCtrl">
<div class="wrapper">
<!-- Let us your email -->
<div class="">
<h2 class="text-center">Subscribe to our news</h2>
<div class="col-lg-4 col-lg-offset-4 mt centered">
<h4 ng-hide="mailchimp.result ==='success'">LET ME KNOW WHEN YOU LAUNCH</h4>
<h4 ng-show="mailchimp.result ==='success'">THANKS FOR SIGNING UP!</h4>
</div>
<form class="form-inline" role="form" ng-hide="mailchimp.result === 'success'">
<input class="hidden" type="hidden" ng-model="mailchimp.username" ng-init="mailchimp.username='stopappweb'">
<input class="hidden" type="hidden" ng-model="mailchimp.dc" ng-init="mailchimp.dc='us12'">
<input class="hidden" type="hidden" ng-model="mailchimp.u" ng-init="mailchimp.u='3eb39be3ad857e60b357fdb5e'">
<input class="hidden" type="hidden" ng-model="mailchimp.id" ng-init="mailchimp.id='520ddfd981'">
<div class="form-group">
<label class="sr-only" for="mailchimp.email">Email address</label>
<input type="email" class="form-control" id="mailchimp.email" placeholder="Enter email" ng-model="mailchimp.email">
</div>
<button type="submit" class="btn btn-info" ng-disabled="MailchimpSubscriptionForm.$invalid" ng-click="addSubscription(mailchimp)" type="submit" value="SIGN UP" disabled="disabled">Submit</button>
<div ng-show="mailchimp.result === 'error'">
<p ng-bind-html="mailchimp.errorMessage" class="error"></p>
</div>
</form>
</div>
</div>
</section>
And this is my JS:
'use strict';
angular.module('mailchimp', ['ng', 'ngResource', 'ngSanitize'])
.controller('MailchimpSubscriptionCtrl', ['$log', '$resource', '$scope',
function ($log, $resource, $scope) {
$scope.myData = new Firebase("https://stopappwebpre.firebaseio.com/subscriptors");
// Handle clicks on the form submission.
$scope.addSubscription = function (mailchimp) {
var actions,
MailChimpSubscription,
params,
url;
$scope.myData.push({mailchimp.email:$scope.mailchimp.email});
// Create a resource for interacting with the MailChimp API
url = 'http://' + mailchimp.username + '.' + mailchimp.dc + '.list-manage.com/subscribe/post-json';
params = {
'EMAIL': mailchimp.email,
'FNAME': mailchimp.fname,
'LNAME': mailchimp.lname,
'c': 'JSON_CALLBACK',
'u': mailchimp.u,
'id': mailchimp.id
};
actions = {
'save': {
method: 'jsonp'
}
};
MailChimpSubscription = $resource(url, params, actions);
// Send subscriber data to MailChimp
MailChimpSubscription.save(
// Successfully sent data to MailChimp.
function (response) {
// Define message containers.
mailchimp.errorMessage = '';
mailchimp.successMessage = '';
// Store the result from MailChimp
mailchimp.result = response.result;
// Mailchimp returned an error.
if (response.result === 'error') {
if (response.msg) {
// Remove error numbers, if any.
var errorMessageParts = response.msg.split(' - ');
if (errorMessageParts.length > 1)
errorMessageParts.shift(); // Remove the error number
mailchimp.errorMessage = errorMessageParts.join(' ');
} else {
mailchimp.errorMessage = 'Sorry! An unknown error occured.';
}
}
// MailChimp returns a success.
else if (response.result === 'success') {
mailchimp.successMessage = response.msg;
}
},
// Error sending data to MailChimp
function (error) {
$log.error('MailChimp Error: %o', error);
}
);
}; }]);
Thank you so much for your help.
Hi i started learning AngularJs and now im trying to do my Login module using angular and php, but i have some issues. I have watched alot tutorials but none of them was helpful in my case, so here is what i have: controllers.js:
var controllers = angular.module('controllers', []);
controllers.controller('loginController', ['$scope', '$http', 'UserService', function(scope, $http, User) {
scope.main = [
{username: '', password: ''}
]
scope.login = function(){
var config = {
url: '../auth/login.php',
method: 'POST',
data: {
username: scope.main.username,
password: scope.main.password
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}
$http(config)
.success(function(data,status,headers,config){
if(data.status){
//succefull login
User.isLogged = true;
User.username = data.username;
}
else{
User.isLogged = false;
User.username = '';
}
})
.error(function(data,status,headers,config){
User.isLogged = false;
User.username = '';
});
}
}])
auth.js:
var services = angular.module('services', []);
services.factory('UserService', [function(){
var sdo = {
isLogged: false,
username: ''
};
return sdo;
}]);
login.php:
$username = $_POST['username'];
if($username){
return "Logged";
}else{
return false;
}
and the html:
<div class="col-xs-12" id="loginCol" ng-controller="loginController">
<form ng-submit='login()' name="form" novalidate>
<div class="form-group">
<label for="username" class="sr-only">Username</label>
<input type="text" ng-model="scope.main.username" class="form-control" id="username" placeholder="Име..." />
<label for="password" class="sr-only">Password</label>
<input type="password" ng-model="scope.main.password" class="form-control" id="password" placeholder="Парола..." />
</div>
<div class="form-group pull-right">
<button type="button" class="btn btn-primary">Login</button>
<button type="button" class="btn btn-default">Register</button>
</div>
</form>
</div>
In this case i want just if user type something in the username input and hit the login button and on successful call of login.php to return some message. The problem is that code written like that got error "'loginController' is not a function, got undefined" how to fix it?
(Disclosure: I'm one of the developers of UserApp)
You could try the third-party service UserApp, together with the AngularJS module.
Check out the getting started guide, or take the course on Codecademy. Here's some examples of how it works:
Login form with error handling:
<form ua-login ua-error="error-msg">
<input name="login" placeholder="Username"><br>
<input name="password" placeholder="Password" type="password"><br>
<button type="submit">Log in</button>
<p id="error-msg"></p>
</form>
Signup form with error handling:
<form ua-signup ua-error="error-msg">
<input name="first_name" placeholder="Your name"><br>
<input name="login" ua-is-email placeholder="Email"><br>
<input name="password" placeholder="Password" type="password"><br>
<button type="submit">Create account</button>
<p id="error-msg"></p>
</form>
ua-is-email means that the username is the same as the email.
How to specify which routes that should be public, and which route that is the login form:
$routeProvider.when('/login', {templateUrl: 'partials/login.html', public: true, login: true});
$routeProvider.when('/signup', {templateUrl: 'partials/signup.html', public: true});
The .otherwise() route should be set to where you want your users to be redirected after login. Example:
$routeProvider.otherwise({redirectTo: '/home'});
Log out link:
<a href="#" ua-logout>Log Out</a>
Access user properties:
User info is accessed using the user service, e.g: user.current.email
Or in the template: <span>{{ user.email }}</span>
Hide elements that should only be visible when logged in:
<div ng-show="user.authorized">Welcome {{ user.first_name }}!</div>
Show an element based on permissions:
<div ua-has-permission="admin">You are an admin</div>
And to authenticate to your back-end services, just use user.token() to get the session token and send it with the AJAX request. At the back-end, use the UserApp API with the PHP library to check if the token is valid or not.
If you need any help, just let me know :)
You have created the application
var controllers = angular.module('controllers', []);
but didn't use it in the html code, add ng-app attribute to the wrapper div
<div class="col-xs-12" ng-app="controllers" id="loginCol" ng-controller="loginController">
the second issue, that you try to catch submit event, but don't submit the form, use submit type instead button
<button type="submit" class="btn btn-primary">Login</button>
or add ng-click="login()" attribute to the button and remove ng-submit='login()' from the form