I'm trying to build a donation form using angular-payments and sending the data to an Expressjs server.
Currently I'm having trouble getting my form to post data other than the data that angular-payments sends. How can a post data that's not part of the angular-payments scope using the same controller?
Here is my Angular script:
angular.module('donate', ['angularPayments'])
function DonateCtrl($scope, $http) {
$scope.handleStripe = function(status, response){
console.log('response', status, response);
if(response.error) {
console.log('error');
// there was an error. Fix it.
} else {
// got stripe token, now charge it or smt
console.log('no error');
var token = response.id;
console.log(token);
return $http.post('http://localhost:8181/api/payments', response)
}
}
};
And here's the HTML:
<form stripe-form="handleStripe" name="donateForm">
<h3>Credit Card Details</h3>
<label for="">Card number</label>
<input type="text" name="number" ng-model="number" payments-validate="card" payments-format="card" payments-type-model="type" ng-class="donateForm.number.$card.type" placeholder="4500 0000 0000 0000" />
<label for="">Expiry</label>
<input type="text" ng-model="expiry" payments-validate="expiry" payments-format="expiry" placeholder="01 / 99" />
<label for="">CVC</label>
<input type="text" ng-model="cvc" payments-validate="cvc" payments-format="cvc" payments-type-model="type" placeholder="123" />
<h3>Donor Details</h3>
<label for="name">Name on card </label>
<input type="text" name="name" ng-model="name" placeholder="John Smith">
<label for="address">Street Address</label>
<input type="text" name="address" ng-model="addressLine1" placeholder="123 Any Street" required/>
<input type="text" name="city" ng-model="addressCity" placeholder="Anytown" required />
<input type="text" name="province" ng-model="addressState" placeholder="Any Province" ng-required="addressCountry == 'Canada' || addressCountry == 'United States'" />
<select data-placeholder="Choose a Country" name="country" ng-model="addressCountry" required>
{% include 'includes/countryselect' %}
</select>
<input type="text" name="postcode" ng-model="addressZip" placeholder="A1B 2C3" ng-required="addressCountry == 'Canada' || addressCountry == 'United States'" />
<div ng-show="donateForm.addressLine1.$pristine && donateForm.addressLine1.$invalid || donateForm.addressCity.$pristine && donateForm.addressCity.$invalid || donateForm.addressState.$pristine && donateForm.addressState.$invalid || addressCountry.$pristine && addressCountry.$invalid || donateForm.addressZip.$pristine && donateForm.addressZip.$invalid" class="help-block">Enter your full home address.</div>
<label for="phone">Phone Number <small>(include country & area code)</small></label>
<input type="tel" name="phone" ng-model="phone" placeholder="+1 204-555-5555" required />
<div ng-show="donateForm.phone.$invalid && donateForm.phone.$pristine" class="help-block">Enter your phone number.</div>
<label for="email">Email Address</label>
<input type="email" name="email" ng-model="email" placeholder="johnsmith#email.com" required />
<div ng-show="donateForm.email.$invalid && donateForm.email.$pristine" class="help-block">Enter your email address.</div>
<button type="submit">Submit</button>
When you say post additional data, do you mean send data with the POST request?
This is how I do it as an example:
$http({
url: 'http://localhost:8181/api/payments',
method: 'POST',
data: {
key: value,
key2: value
}).success(function(data) {
// If successful
}).error(function(data) {
// If error
return data.message;
});
Related
I'm just starting with JS and like to implement a form that verifies for robots/humans by using captcha v3 on the client side and if verification succeeds the data should be submitted to another file.
This is what I got so far. I know it's wrong, but unsure what the correct logic is. Hope someone can shed a light. Thx!
<script src="https://www.google.com/recaptcha/api.js?render=6Lc3UZkeAAAAAMt6wcA-bYjLenFZPGv3K5AqfvuQ"></script>
<script type="text/javascript" src="/js/libs/jquery-1.11.3.min.js"></script>
<section class="cc-column-component regular-grid">
<form id="bank-form" class="form clear one-full cf-contact-form" action="?" method="POST" data-tracking="contact_sales">
<div>
<label class="label mandatory bank-color bank-label" for="firstName">First Name</label>
<input id="firstName" value="Pepe" type="text" class="one-full bank-color-grey bank-input" name="firstName" placeholder="First Name" autocomplete="off" data-validate="true" data-type="text" data-min="3" value="<?php isset($this) ? print $this->getFirstName() : print ''; ?>">
<br/>
<label class="label mandatory bank-color bank-label" for="lastName">Last Name</label>
<input id="lastName" value="Chanches" type="text" class="one-full bank-color-grey bank-input" name="lastName" placeholder="Last Name" autocomplete="off" data-validate="true" data-type="text" data-min="3" value="<?php isset($this) ? print $this->getLastName() : print ''; ?>">
<br/>
<label class="label mandatory bank-color bank-label" for="email">Email</label>
<input value="asdf#asdf.com" id="email" type="text" class="one-full bank-color-grey bank-input" name="email" placeholder="Email" autocomplete="off" data-validate="true" data-type="email" value="<?php isset($this) ? print $this->getEmail() : print ''; ?>">
<br/>
</div>
<div class="row inline one-full">
<br/>
<!-- <div class="g-recatpcha" data-sitekey="6Lc3UZkeAAAAAMt6wcA-bYjLenFZPGv3K5AqfvuQ"></div> -->
<button type="submit"
id="form-submit"
value="submit"
>
<a>Submit form</a>
</button>
<div class="field inline one-full">
<br/>
</div>
<!-- <input type="hidden" name="recaptcha_response" id="recaptchaResponse"> -->
</div>
</form>
</section>
<script>
$('#bank-form').submit(function(event) {
console.log('subtmitting');
event.preventDefault();
grecaptcha.ready(function() {
grecaptcha.execute('6Lc3UZkeAAAAAMt6wcA-bYjLenFZPGv3K5AqfvuQ', {action: 'submit'}).then(function(token) {
console.log('🚀 ~ grecaptcha.execute ~ token', token)
$('#bank-form').prepend('<input type="hidden" name="token" value="' + token + '">');
$('#bank-form').prepend('<input type="hidden" name="action" value="submit">');
// $('#bank-form').unbind('submit').submit();
});;
});
CheckCaptcha(token)
});
function CheckCaptcha(token) {
var token = $("#token").val()
console.log('🚀 ~ token', token)
var action = $("#action").val()
var RECAPTCHA_V3_SECRET_KEY = "6Lc3UZkeAAAAAIG8bVZDpkheOxM56AiMnIKYRd6z"
$.ajax({
type: "POST",
url: "http://www.google.com/recaptcha/api/siteverify",
data: JSON.stringify([{secret: RECAPTCHA_V3_SECRET_KEY }, {response : token }]),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// __doPostBack('form-submit', '');
if(response["score"] >= 0.7) {
console.log('Passed the token successfully');
}
},
failure: function (response) {
// set error message and redirect back to form?
console.log('Robot submit', response);
}
})
return false;
}
</script>
function checkRegisterError() {
const xhr = new XMLHttpRequest();
xhr.open("GET", "http://ipaddressandport/users/register");
xhr.onload = () => {
console.log("tes");
if (xhr.status === 400) {
console.log("rip");
}
};
xhr.send();
}
const signupBtn = document.querySelector(".signup-form-btn");
if (signupBtn) {
signupBtn.addEventListener("click", () => {
console.log("ok");
checkRegisterError();
});
}
I'm using nodejs and express. So I have this applied on my register button which is also a type submit for a form with an action of /users/register. On my node I have this code which is registered to /users/register:
exports.addUser = (request, respond) => {
if (
!request.body.firstName ||
!request.body.lastName ||
!request.body.email ||
!request.body.username ||
!request.body.password ||
!request.body.gender ||
!request.body.mobileNumber ||
!request.body.address
) {
respond.status(400).send("error empty input etc etc");
} else {
db.execute(
"INSERT INTO users(firstName, lastName, email, username, password, gender, mobileNumber, address, profilePictureUrl) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)",
[
request.body.firstName,
request.body.lastName,
request.body.email,
request.body.username,
request.body.password,
request.body.gender,
request.body.mobileNumber,
request.body.address,
"https://www.eurogeosurveys.org/wp-content/uploads/2014/02/default_profile_pic.jpg",
]
)
.then((result) => {
console.log(result);
respond.redirect("/");
})
.catch((err) => console.log(err));
}
};
The problem is whenever I press register the forms goes to the route and it will be a blank page of whatever I sent, and there will be no logged output. I want to change certain element properties depending on what the message and status code is. How could I do that? Why am I getting directed to an empty page with the text I sent?
<form class="sign-up-form" action="/users/register" method="POST">
<div class="nav-name">
<input name="firstName" type="text" class="input first-name" placeholder="First name">
<input name="lastName" type="text" class="input last-name" placeholder="Last name">
</div>
<input name="email" type="text" class="input email" placeholder="Email">
<input maxlength="16" name="username" type="text" class="input username" placeholder="User ID">
<div class="password-container">
<input maxlength="16" name="password" type="password" class="input password" placeholder="Password">
<label class="toggle-password" for="toggle-password-register">
<i class="show-password fas fa-eye"></i>
<i class="hide-password fas fa-eye-slash"></i>
</label>
<input id="toggle-password-register" type="checkbox" class="toggle-password__input">
</div>
<input name="gender" type="text" class="input gender" placeholder="Gender">
<input name="mobileNumber" type="text" maxlength="8" class="input mobile-number"
placeholder="Mobile number">
<input name="address" type="text" class="input address" placeholder="Address">
<button type="submit" class="form-btn signup-form-btn">Sign up</button>
</form>
You are getting redirected to empty page because you have written response.redirect('/') , you should check if Db operation is successful then according to that send response to user .
I'm trying to create charge using a token created with stripe elements on the front end. I want to add the customers address by binding the different properties of tokenData with ngmodel to inputs, then passing the tokenData object as the second argument of the createToken() method.
//component.html
<input type="text" [(ngModel)]="name" placeholder="name" name="name">
<input type="text" [(ngModel)]="address_line1" placeholder="adress line 1" name="address">
<input type="text" [(ngModel)]="address_line2" placeholder="adress line 2" name="address">
<input type="text" [(ngModel)]="address_city" placeholder="City" name="city">
<input type="text" [(ngModel)]="address_state" placeholder="State" name="state">
<input type="text" [(ngModel)]="address_country" placeholder="Country" name="country">
<button (click)="submitForm()">Submit Payment</button>
//component.ts
public tokenData = {
name: '',
address_line1: '',
address_line2: '',
address_city: '',
address_state: '',
address_zip: undefined,
address_country: ''
};
public submitForm = () => {
this.stripe.createToken(this.card, this.tokenData).then(res => {
if(res.error){
console.log(res.error.message);
}
else {
this.stripeTokenHandler(res.token).subscribe();
console.log(res.token);
}
});
};
public stripeTokenHandler(t){
return this.http.post(`${this.apiUrl}/charge`, t);
};
but when I submit the form the token gets logged to the console with the tokenData parameters empty, which means that the inputs aren't getting binding properly to tokenData. How can this be done?
You are not binding to the properties of the tokenData, add tokenData to all your bindings like [(ngModel)]="tokenData.address_line1"
<input type="text" [(ngModel)]="tokenData.name" placeholder="name" name="name">
<input type="text" [(ngModel)]="tokenData.address_line1" placeholder="adress line 1" name="address">
<input type="text" [(ngModel)]="tokenData.address_line2" placeholder="adress line 2" name="address">
<input type="text" [(ngModel)]="tokenData.address_city" placeholder="City" name="city">
<input type="text" [(ngModel)]="tokenData.address_state" placeholder="State" name="state">
<input type="text" [(ngModel)]="tokenData.address_country" placeholder="Country" name="country">
I'm a newbie to angular, so I need a help.
In html, I wrote the following
<div class="form-group">
<input type="email" name="Email" id="LoginEmail class="form-control" placeholder="Email Address" required>
</div>
<div class="form-group">
<input type="password" name="password" id="LoginPassword" class="form-control" placeholder="Password" required>
</div>
In angular, I write the following code
angular
.module("LoginForm", [])
.controller("processingLoginForm", ["$scope", function ($scope) {
$scope.userinfo = [
{name : "User1",
account : "user1#whatever.com",
city: "XYZ",
password: "Angular#2017"}
];
}]);
I need to compare the value of input box with the value of the script and show a message if it's not correct, so how can I do that?
Firstly you need to assign model to your template scope. Use ng-model for this purpose. Then you need a form to submit and trigger a function to check if user input matches to the desired values.
Add ng-model and wrap your inputs with a form tag:
<form ng-submit="login()">
<div class="form-group">
<input ng-model="email" type="email" name="Email" id="LoginEmail" class="form-control" placeholder="Email Address" required>
</div>
<div class="form-group">
<input ng-model="password" type="password" name="password" id="LoginPassword" class="form-control" placeholder="Password" required>
</div>
<button type="submit">Login</button>
</form>
Check if user input is valid in Controller:
$scope.login = function() {
const isUserValid = $scope.email === $scope.userinfo[0].account && $scope.password === $scope.userinfo[0].password;
if(isUserValid) {
alert("Logged In Successfully");
}else {
alert("Email or password incorrect. Try again.")
}
}
Here's a working example of the above code.
In your input elements you miss the ng-model attribute. It is used to bind the values with your scope variables.
<input type="email" ... ng-model="email" ...>
<input type="password" ... ng-model="password" ...>
And in your controller you can write
if($scope.email == $scope.userinfo[0].account && $scope.password == $scope.userinfo[0].password){
//Login ok
}else{
//Login failed
}
Assuming there is a form element somewhere above
Add ng-submit to it
<form ng-submit="submit()">
Add ng-model to the form elements.
I have added state.email and state.password
<div class="form-group">
<input ng-model="state.email" type="email" name="Email" id="LoginEmail" class="form-control" placeholder="Email Address" required>
</div>
<div class="form-group">
<input ng-model="state.password" type="password" name="password" id="LoginPassword" class="form-control" placeholder="Password" required>
</div>
Compare the binding values to the values in $scope.userinfo
angular
.module("LoginForm", [])
.controller("processingLoginForm", ["$scope", function ($scope) {
$scope.userinfo = [{
name : "User1",
account : "user1#whatever.com",
city: "XYZ",
password: "Angular#2017"
}];
// when you submit the form, this function will be called
$scope.submit = function (e) {
e.preventDefault();
if ($scope.state.email !== $scope.userinfo[0].account || $scope.state.password !== $scope.userinfo[0].password) {
// did not match
} else {
// matched
}
}
}]);
This is my first bigger form with validations and etc.
I've created a Registration form and I'm using ng-messages for validation. The problem is that I need to validate the username, does it already exist in the JSON server that we are using or it's available. Of course, if it's taken the warning pops out in the HTML where the username input is, if it's available the submit button is no more disabled (because the form will be $valid) and the user can register. I want to use angular-sanitize because I found this (I don't know if they are related):
ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
var value = modelValue || viewValue;
// Lookup user by username
return $http.get('/api/users/' + value).
then(function resolved() {
//username exists, this means validation fails
return $q.reject('exists');
}, function rejected() {
//username does not exist, therefore this validation passes
return true;
});
};
Here is the code I use now (reg form, controller and service):
// Controller:
export default class registerPageController {
constructor(userService, authenticationService, $location) {
this.register = "Register";
this.userService = userService;
this.$location = $location;
this.authenticationService = authenticationService;
this.hasLoggedIn = false;
}
onSubmit(user) {
let self = this;
let {
name,
age,
email,
username,
password
} = user;
self.userService.register(name, age, email, username, password).then((res) => {
self.userService.login(username, password).then(function (response) {
let data = response.data;
if (data.length) {
let user = data[0];
self.hasLoggedIn = true;
self.authenticationService.setCredentials(username, password);
self.$location.path('/');
}
});
})
.catch(err => {
// WHAT TO PUT HERE AFTER THE USERNAME EXIST VALIDATION ?
})
}
}
// Service:
export class UserService {
constructor($http) {
this.$http = $http;
}
login(username, password) {
return this.$http({
method: 'GET',
url: 'http://localhost:3000/users',
params: {
username: username,
password: password
}
});
}
register(name, age, email, username, password) {
return this.$http({
method: 'POST',
url: 'http://localhost:3000/users',
data: {
name: name,
age: age,
email: email,
username: username,
password: password
}
});
}
// SHOULD I PUT HERE THE USERNAME EXIST VALIDATION LOGIC ?
}
<div class="container main-content">
<form class="registrationForm" name="registerForm" ng-submit="register.onSubmit(register.user)" novalidate="novalidate">
<!-- Enter Name -->
<div class="form-group">
<label for="name" class="control-label"><span id="reqInfo">*</span> Name</label>
<input type="text" name="name" class="form-control" ng-model="register.user.name" ng-pattern="/[a-zA-Zа-яА-Я]+/" id="name"
required="" placeholder="Example: Petar Petrov">
<div ng-messages="registerForm.name.$error" ng-show="registerForm.name.$touched" style="color:maroon" role="alert">
<div ng-message="required">Your name is required</div>
</div>
</div>
<!-- User Age-->
<div class="form-group">
<label for="age" class="control-label"><span id="reqInfo">*</span> Age</label>
<input type="number" name="age" class="form-control" ng-model="register.user.age" ng-min="18" min="18" id="age" required=""
placeholder="Enter your age">
<div ng-messages="registerForm.age.$error" ng-show="registerForm.age.$touched" style="color:maroon" role="alert">
<div ng-message="min">You must be at leats 18 years old</div>
</div>
</div>
<!-- Enter E-mail -->
<div class="form-group">
<label for="email" class="control-label"><span id="reqInfo">*</span> E-mail</label>
<input type="email" name="email" class="form-control" ng-model="register.user.email" ng-pattern="/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+#)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+#)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%#\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/"
id="email" required="" placeholder="Example: mail#mail.net">
<div ng-messages="registerForm.email.$error" ng-show="registerForm.email.$touched" style="color:maroon" role="alert">
<div ng-message="required">Your valid e-mail is required</div>
</div>
<br>
<!-- Enter Username -->
<div class="form-group">
<label for="username" class="control-label"><span id="reqInfo">*</span> Username</label>
<input type="text" name="username" ng-minlength="5" ng-maxlength="20" class="form-control" ng-model="register.user.username"
ng-pattern="/^[A-Za-z0-9_]{1,32}$/" ng-minlength="7" id="username" required="" placeholder="Enter your username">
<div ng-messages="registerForm.username.$error" style="color:maroon" role="alert">
<div ng-message="minlength">Your Username must be between 7 and 20 characters long</div>
</div>
<br>
<!-- Enter Password -->
<div class="form-group">
<label for="password" class="control-label"><span id="reqInfo">*</span> Password</label>
<input type="password" name="password" class="form-control" ng-model="register.user.password" ng-minlength="7" id="password"
required="" placeholder="Enter your password">
<div ng-messages="registerForm.password.$error" style="color:maroon" role="alert">
<div ng-message="minlength">You Password must be at least 7 symbols long</div>
</div>
</div>
<!-- Register button -->
<div class="form-group">
<button class="btn btn-primary" type="submit" ng-disabled="!registerForm.name.$valid || !registerForm.age.$valid || !registerForm.email.$valid || !registerForm.username.$valid || !registerForm.password.$valid">Register</button>
</div>
<p>Fields with <span id="reqInfo">*</span> must be filled.</p>
</form>
</div>
Important is to know that I have being told explicitly to write it in ES6.
I have problem with the logic so look at my code and please fill it for me so I can use it and most important - learn it :S
Thank you so so much in advance!
I have implemented a directive for different kind of validations (sync Async), and it supports warning as well.
You may check it from
`https://plnkr.co/2WQHOo`
If this is what you needed and need more information, let me know I will try my best to answer.