How to get formData from Angular-Payments - javascript

I am using Angular-Payments that intercepts the form data and submits it to Stripe. This works well, however, I'm not sure how to access form data after its sent to stripe. For example, my form has quantity field which I would like to get access to but I don't know how to...
Here is what I'm doing HTML
<form stripe-form="handleStripe" role="form" ng-if="authenticated" name="takeMoneyForm" ng-submit="takeMoney(takeMoneyForm, model)">
<input type="text" name="card_number" ng-model="number" payments-validate="card" payments-format="card" payments-type-model="type" ng-class="takeMoneyForm.number.$card.type">
<input type="text" name="card_cvc" ng-model="cvc" payments-validate="cvc" payments-format="cvc" payments-type-model="type">
<input type="text" nam="card_expiry" ng-model="expiry" payments-validate="expiry" payments-format="expiry">
<input type="text" ng-model="quantity"/>
<button class='form-control submit-button btn btn-majoo' type='submit'>Pay ยป</button>
</form>
JS
$scope.takeMoney = function(formData, model){
$scope.handleStripe = function(status, response){
if(response.error) {
// there was an error. Fix it.
alert("Error happened")
} else {
var dataModel = {
email: model.email,
profile: {
stripe_token: response.id,
stripe_id: model.profile.stripe_id
//here I would like to get access to the quantity from the form
}
}
djangoAuth.takeMoney(dataModel)
$scope.complete = true;
}
}
}
I feel like this should be simple but I'm very new to Angular and can't seem to figure this out.

since youre using ng-model the values of those fields should be on that form's scope(as in scope.number)
If they are not accessible it could be one of two things:
1) Angular Payments clears the ng-model following submit
2) you are trying to access it from a different scope.

Related

How to validate empty text box for mandatory field in button click in angular js

Can anybody tell How to validate empty text box for mandatory field in button click in angular js after validate i need to call web service call .Can anybody tell how to implement?
Use this:
<form name="yourForm">
<input name="name" ng-model="model.name" type="text" required />
<div ng-messages="yourForm.name.$error">
<div ng-message="required">Name is required!</div>
</div>
<button ng-click="send()">Send</button>
</form>
And in controller js:
$scope.send = function () {
if ($scope.yourForm.$valid) {
// TODO: send model to server
}
}
Don't forget:
Include Angular ngMessages module in your app.
Good luck
You can use 'required' attribute to make sure they enter a value in the field
<input type="text" name="userName" ng-model="user.name" required>
For the service call you can have a javascript method onClick , for example:
<button type="button" class="button" name="Search" id="searchButton" ng-click="getUserInfo()">Search</button>
then you do an ajax call in the Angular module
$scope.getUserInfo = function()
{
if ($scope.fetchData)
{
var data = {
func: "USERINFO",
searchUserId: $('#searchUserId').val()
};
$http({method:'POST',
url:'/MYAPP/getuser',
data: $.param(data),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
.success(function(data, status, header, config) {
$scope.users = data;
})
.error(function(data,status, headers, config) {
alert('Error getting user infos ');
})
}
}
This is a quick example. the /MYAPP/getuser maps to a REST service that returns the data in JSON format. The success(function) is what gets executed when the call is executed successfully and the data is returned. You can bind the returned data to an angular table or control for display.
.error is executed if the call fails
As for the REST services, You can write it in JAVA or C# or whatever language you like, as long as it returns JSON.

Input from the form is not passed to the controller and keeps being "undefined"

I have the hardest time dealing with forms and passing values from them to the controller. I have the same story every time: the ng-model and everything is set up but the controller is not accepting what I'm trying to pass it and thus gives me that the var is not defined. Would anyone suggest how to deal with this and how to properly setup forms with Angular? Their documentation is darn awful!
Here's the markup of the form:
<div>
<form name="thisForm" ng-submit="submit()" class="wa-id-submit-form">
<label>Submit your number</label>
<input name="wa_id" ng-model="submission" type="text" class="form-control" required />
<input type="submit" class="form-control" name="submit" value="Submit" />
</form>
</div>
Here's the function and the var I'm trying to pass it to:
$scope.submit = function() {
var data = {
"wa_id": $scope.wa_id
};
console.log($scope.wa_id);
var hookphp = submitIdService.submitId();
hookphp.save(data,
function(result){
console.log(result);
};
The php side of this all works just fine and doesn't need to be looked at. I just need to pass that one line from the input to the data variable and it's not. Am I not making the ng-model and such talk properly to each other?
},
function(result){
console.log('NO GO');
}
);
};
You should use corresponding ngModel to access data in controller, not input name:
var data = {
wa_id: $scope.submission
};
I have been reminded of something very important when dealing with ng-models here
The ng-model has to have a .notation in it to function properly. It's possible that it would function without it as well, but even people who help develop Angular strongly recommend using it with a "."
Here's what had to be done with my code:
<form ng-submit="submit()" class="wa-id-submit-form">
<label>Submit your number</label>
<input name="waid" ng-model="waid.submission" type="text" class="form-control" required />
<input type="submit" class="form-control" name="submit" value="Submit" />
</form>
an ng:
$scope.waid = {};
$scope.submit = function() {
var data = {
"wa_id": $scope.submission
};
var hookphp = submitIdService.submitId();
hookphp.save(data,
function(result){
console.log(result);
},
function(result){
console.log('NO GO');
}
);
};
An object had to be declared "empty" prior to being able to use it in the function as well.

ng-show/ng-hide loops when a "submit()" added, making the browser crash

I am trying to add an error message with an either ng-show or ng-hide.
<p ng-show="submit()">Incorrect login/password.</p>
<form method="POST" name="adminform" ng-submit="submit()" class="admin-login-form">
<label for="username">Admin Login</label>
<input ng-model="username" type="text" name="username" class="form-control" required autofocus="yes"/>
<label for="password">Password</label>
<input ng-model="password" type="password" name="password" class="form-control" required />
<input type="submit" class="form-control" name="submit" value="Login" required/>
</form>
Ideally, the show/hide needs to be activated when submit() was run and did not succeed on login. However, when I do ng-show="submit()" it works but keeps refreshing itself and looping, making the browser crash and giving an error in the console even if the submit button itself hasn't been clicked.
$scope.submit = function() {
var data = {
'username': $scope.username,
'password': $scope.password
};
var hookphp = loginService.login();
hookphp.save(data,
function(result){
$location.path("dashboard");
},
function(){
alert('Invalid password/login.');
}
);
};
Also, it never gives me the alert when the login is not successful. Could anyone suggest how to do this properly? I am still in the process of figuring out how Javascript and Angular work. Thanks a lot!
<p ng-show="errorVisible">Incorrect login/password.</p>
In angular
$scope.errorVisible = true/false (set it whenever you need it)
So:
$scope.errorVisible = false;
$scope.submit = function() {
var data = {
'username': $scope.username,
'password': $scope.password
};
var hookphp = loginService.login();
hookphp.save(data,
function(result){
$location.path("dashboard");
$scope.errorVisible = false; //optional
},
function(){
$scope.errorVisible = true;
}
);
};
Also the reason it's looping forever in your initial code is that ng-show keeps calling the function, but the function doesn't return anything.
On your code, it seems like your function is not returning either true or false depending on the login status, so in that case, since function call is success, the output of the function will always be true causing your login failure label will be visible at all times.
As #MrVentzi suggested, it is better to use separate scope variable in order to decide wheter to show the message or not. If you try to do it as
<p ng-show="submit()">Incorrect login/password.</p>
ng-show will be constantly calling and listening to output of the function. In order to show you better, I created this example: http://jsfiddle.net/eytt2d8x/

How to submit a form in Angular

I have an html form that I am validating with an Angular controller. If the validation fails, I apply certain classes to the html. If it passes, I want to let the form submit itself. Although this seems very straightforward, I haven't found an easy way to do this. One method I have found uses the $scope.$broadcast function to tell the form to submit, however, I am using the Controller as Ctrl syntax so I would rather not use $scope. Is there anyway to submit a form from a controller?
My simplified HTML
<form ng-controller="LoginCtrl as login" ng-submit="login.validate()" method="post">
<input ng-model="login.username" />
<input ng-model="login.password" />
</form>
JS
var app = angular.module("app", []);
app.controller("LoginCtrl", ["$http", function($http) {
this.username = "";
this.password = "";
this.validate = function() {
//validate
if (valid) {
// somehow form.submit()
}
};
}]);
I am somewhat new to Angular so forgive me if this is an obvious quesion ;)
EDIT:
I need to clarify that I am looking to avoid submitting the form with AJAX (i.e. $http.post). Basically what I want is the controller equivalent of calling form.submit().
USE CASE:
Let me explain exactly what I am trying to do.
User arrives at login page
User enters credentials
User hits Submit
Controller asks server (using api path) if the credentials are valid
if valid then
Tell the form to submit to regular login path // how?
else
Immediately tell the user they submitted invalid credentials
This way the User gets immediate feedback if they entered incorrect credentials.
All of this I have implemented except for the actual form submission.
Simplest approach would be wrap all the form element data into one object. You don't have to create this object if you have no data to prepopulate, ng-model will create it for you.
<form ng-controller="LoginCtrl as login" ng-submit="login.validate()" method="post">
<input ng-model="login.MyFormData.username" />
<input ng-model="login.MyFormData.password" />
</form>
This will result in an object in your controller scope looking like:
$scope.MyFormData={
username :'foo',
password:'bar'
}
When ready to submit:
$http.post('path/to/server', $scope.myFormData).success(response){
/* do something with response */
})
I have an example with the bare minimum code here. Note, it is self validating, and you don't even need to submit anything from the COntroller! you can include the action and method fields as form attributes, and angular will submit the form if it is valid
HTML
<form name="LoginCtrl as loginForm" method="Post" action="not-a-real-script.php">
<input type="text" name="name" ng-model="loginData.name" placeholder="username" required="" />
<input type="password" name="password" ng-model="loginData.password" placeholder="Password" required />
<input type="submit" ng-disabled="loginForm.$invalid" value="Login" />
</form>
JS
angular.module('app', [])
.controller('LoginCtrl', function($scope) {
$scope.loginData = {};
});
I think you want to have validation as part of your form submission flow. Try something like this:
HTML
<form ng-controller="LoginCtrl as login" ng-submit="login.submit()" method="post">
<input ng-model="auth.username" />
<input ng-model="auth.password" />
<div class="error" ng-hide="valid">Something is invalid...</div>
</form>
JS
var app = angular.module("app", []);
app.controller("LoginCtrl", ["$http", "$scope", function($http, $scope) {
$scope.valid = true;
$scope.auth.username = "";
$scope.auth.password = "";
var valid = function() {
// validate
return valid; // true or false
};
this.submit = function() {
if (valid()) {
$http.post('/your/auth/url', { auth: auth }).success(function(response) {
// whatever you're doing to store the auth response.
});
} else {
// use this to conditionally show error messages with ng-show
$scope.valid = false;
}
};
}]);
I'm not sure I understand your comment about using the controller-as syntax. That shouldn't change how you use $scope.

Dynamically duplicated forms disappear on CodeIgniter reload

I have the following code that needs to be duplicated:
<form method="post">
<div id="field-row-container">
<div id="field-row-1" class="field-row">
<div class="field-element">
<label for="Name[1]">Name</label>
<input type="text" id="Name[1]" name="Name[]" />
</div>
<div class="field-element">
<label for="Email[1]">Email</label>
<input type="text" id="Email[1]" name="Email[]" />
</div>
<hr/>
</div>
</div>
<div class="form-element">
<input type="button" class="confirm add-field-row" value="Add" />
<input type="button" class="danger delete-field-row" value="Delete" />
<input type="submit" />
</div>
The duplicated / dynamically added elements will have the same names of Name[] and Email[] but their ID's will be incremented.
The JavaScript is below, based from Josiah Ruddell's form duplication script.
var template = $('#field-row-container #field-row-1').clone();
window.addForm = function () {
var parent = $(this).closest('.dynamic-rows').attr('id');
var fieldRowCount = countRows(parent) + 1;
var newFieldRow = template.clone().find(':input').each(function () {
var newId = this.id.substring(0, this.id.length - 3) + "[" + fieldRowCount + "]";
$(this).prev().attr('for', newId); // update label for
this.id = newId; // update id and name (assume the same)
$(this).closest('.field-row').addClass('new-row');
}).end()
.attr('id', 'field-row-' + fieldRowCount)
.appendTo('#field-row-container');
}
$('.add-field-row').click(addForm);
Whenever I submit the form to CodeIgniter and if there is a validation error, once the controller reloads the multi-part form, the dynamically added elements disappear as well as the values in the initial fields.
How do I go around this problem? I'm at a loss on how to solve this...
Other notes that might help:
This is a component multi-part form with only one form controller
I have multiple instances of this - Addresses, Education Degrees and such
I use CodeIgniter's form_validation library to check server-side each array of posts
When the page with the form on reloads after the controllers redirects back to it after failing validation, it will only reload the original page, with no DOM manipulations applied.
I would perform the POST request which submits the form via ajax, so you can handle the response without leaving the page. Something like this:
$.post('/locationOfController.php', $('#yourForm').serialize(), function(response){
if(response.valid){
window.location.href = '/somewhereAfterFormPosted.php';
} else {
$('#yourForm').append("<p>"+response.error+"</p>");
}
}, 'json');
and change the controller to return a JSON object based on whether validation passed or not. To match up with my example above, you would return something like below when an error occurs:
{valid: false, error: 'Please fill out the whole form'}
Try something like that as a basic example. You could do much more, such as returning several errors if multiple fields are invalid.

Categories

Resources