I am currently working on Angular Js with Sql Database . I am trying to creating user registration system though Angular Js with Sql Database but when I click the submit button I got following error ...
angular.js:14642 TypeError: $ is not a function
at b.$scope.SaveUser (Module.js:6)
at fn (eval at compile (angular.js:15500), <anonymous>:4:144)
at e (angular.js:27285)
at b.$eval (angular.js:18372)
at b.$apply (angular.js:18472)
at HTMLInputElement.<anonymous> (angular.js:27290)
at kg (angular.js:3771)
at HTMLInputElement.d (angular.js:3759
Here is code in Register Controller...
public class RegisterController : Controller
{
public ActionResult Register()
{
return View();
}
//To check that user entered is already present or not.
public bool CheckUser(string user)
{
bool Exists = false;
using (HalifaxDatabaseEntities context = new HalifaxDatabaseEntities())
{
var uName = context.UserLogins.Where(x => x.UserName == user).ToList();
if (uName.Count != 0)
{
Exists = true;
}
}
return Exists;
}
//For saving the user details in database table.
public string AddUser(UserLogin usr)
{
if (usr != null)
{
if (CheckUser(usr.UserName) == false)
{
using (HalifaxDatabaseEntities context = new HalifaxDatabaseEntities())
{
UserLogin createUser = new UserLogin();
createUser.UserName = usr.UserName;
createUser.Firstname = usr.Firstname;
createUser.Lastname = usr.Lastname;
createUser.Email = usr.Email;
createUser.DateTimeCreated = DateTime.Now;
createUser.Password = Utility.Encryptpassword(usr.Password);
context.UserLogins.Add(createUser);
context.SaveChanges();
}
return "User created !";
}
else
{
return "User already present !";
}
}
else
{
return "Invalid Data !";
}
}
}
}
Here is my Code for Module.js ..
var app = angular.module("myApp", [])
.controller('Ctrl', ['$scope', function ($scope) {
$scope.SaveUser = function () {
$("#divLoading").show();
var User = {
FName: $scope.fName,
LName: $scope.lName,
Email: $scope.uEmail,
Password: $scope.uPwd,
UserName: $scope.uName
};
var response = myService.AddUser(User);
response.then(function (data) {
if (data.data == "1") {
$("#divLoading").hide();
clearFields();
alert("User Created !");
window.location.href = "/Register/Login";
}
else if (data.data == "-1") {
$("#divLoading").hide();
alert("user alraedy present !");
}
else {
$("#divLoading").hide();
clearFields();
alert("Invalid data entered !");
}
});
}
function clearFields() {
$scope.fName = "";
$scope.lName = "";
$scope.Email = "";
$scope.Password = "";
$scope.UserName = "";
}
}])
.service("myService", function ($http) {
this.AddUser = function (User) {
var response = $http({
method: "post",
url: "/Register/AddUser",
data: JSON.stringify(User),
dataType: "json"
});
return response;
}
})
Here is my HTML CODE ...
#{
Layout = null;
}
<html ng-app="myApp">
<head>
<title>Register</title>
<script src="~/Scripts/angular.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script src="~/Scripts/MyScript/Module.js"></script>
<link href="~/Content/bootstrap.css" rel="stylesheet" />
</head>
<body>
<div class="container" ng-controller="Ctrl">
<br />
<div class="row">
#*<img src="~/Content/Images/user.png" />*#<h4>Register User</h4>
<hr />
<br />
<div class="col-md-6">
<form name="userForm" novalidate>
<div class="form-horizontal">
<div class="form-group">
<div class="row">
<div class="col-md-3" style="margin-left: 15px; color: #5bc0de;">
First Name :
</div>
<div class="col-md-6">
<input type="text" class="form-control" placeholder="First Name" name="fName" ng-model="fName" required autofocus />
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-3" style="margin-left: 15px; color: #5bc0de;">
Last Name :
</div>
<div class="col-md-6">
<input type="text" class="form-control" placeholder="Last Name" name="lName" ng-model="lName" required autofocus />
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-3" style="margin-left: 15px; color: #5bc0de">
Email :
</div>
<div class="col-md-6">
<input type="email" class="form-control" placeholder="User's Email" name="uEmail" ng-model="uEmail" required autofocus />
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-3" style="margin-left: 15px; color: #5bc0de;">
Username :
</div>
<div class="col-md-6">
<input type="text" class="form-control" placeholder="Username" name="uName" ng-model="uName" required autofocus />
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-3" style="margin-left: 15px; color: #5bc0de;">
Password :
</div>
<div class="col-md-6">
<input type="password" class="form-control" placeholder="Password" name="uPwd" ng-model="uPwd" required autofocus />
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-3">
<input type="button" value="Save" ng-click="SaveUser();" class="btn btn-success" />
</div>
<div class="col-md-3">
#Html.ActionLink("Sign in", "Login", "Register", new { #class = "btn btn-info" })
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-6">
<div id="divLoading" style="margin: 0px; padding: 0px; position: fixed; right: 0px; top: 0px; width: 100%; height: 100%; background-color: #666666; z-index: 30001; opacity: .8; filter: alpha(opacity=70); display: none">
<p style="position: absolute; top: 30%; left: 45%; color: White;">
please wait...<img src="~/Content/images/load.png">
</p>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Here is screen shot when I run the application
what is best solution to solved this problem ..Thanks
You will need to include jquery in your scripts path.
Something like this:
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
Make sure you add it before Module.js.
Also to make that function work you will need to add jquery-ui and bootstrap.js.
Related
I have a view that has a button for applying for a job, and this button is redirected to a HttpPost action method that handles the apply logic and then returns a JSON result to the same view. as shown below:
// POST: Application/Apply
[HttpPost]
public ActionResult Apply(string idUser, int idAnnouncement)
{
try
{
// TODO: Add insert logic here
// Search for the candidate that has the same Hash code as idUser param
Candidate appliedCandidate = db.Candidates.Where(c => c.CandidateSecondID.Equals(idUser)).FirstOrDefault();
// todo: check if Candidate is already applyed to job
var check = db.Applications.Where(a => a.CandidateID.Equals(appliedCandidate.CandidateID) && a.AnnouncementID.Equals(idAnnouncement)).FirstOrDefault();
if (check == null)
{
Application newApp = new Application
{
AnnouncementID = idAnnouncement,
CandidateID = appliedCandidate.CandidateID,
ApplicationDate = DateTime.Now,
};
db.Applications.Add(newApp);
db.SaveChanges();
return this.Json(new
{
EnableSuccess = true,
SuccessTitle = "Success",
SuccessMsg = "Your application has been sent successfully!"
});
}
else
{
return this.Json(new
{
EnableSuccess = false,
ErrorTitle = "Warning",
ErrorMsg = "You are already applayed for this Job!"
});
}
}
catch
{
return View();
}
}
Here is the AJAX call:
$.ajax({
method: "POST",
url: action,
success: function (result) {
if (result.EnableSuccess) {
swal(
result.SuccessTitle,
result.SuccessMsg,
'success'
)
} else {
swal(
result.ErrorTitle,
result.ErrorMsg,
'warning'
)
}
},
error: function (err) {
console.log(err);
}
})
and here is the full view :
#model IEnumerable<JobPostingProject.Models.Announcement>
#using Microsoft.AspNet.Identity;
#using Microsoft.AspNet.Identity.Owin;
#{
ViewBag.Title = "List of jobs";
}
#using (Html.BeginForm("Index", "Announcement", FormMethod.Get))
{
<div class="row mb-3">
<div class="col-lg-3 ">
<div class="title">
<i class="fas fa-search mr-2"></i>
<input type="text" name="titleInput" class="title__input form-control border-0" placeholder="Job Title" value="#ViewBag.Job" />
</div>
</div>
<div class="col-lg-3">
<div class="city">
<i class="fas fa-map-marker-alt mr-2"></i>
<input type="text" name="cityInput" class="city__input form-control border-0" placeholder="Location" value="#ViewBag.City" />
</div>
</div>
<div class="col-lg-3">
<div class="categorie">
#Html.DropDownList("Categories", null, "Job Category", new { #class = "form-control" })
</div>
</div>
</div>
<div class="row my-4">
<div class="col-lg-3">
<div class="date mb-4">
#*<i class="fas fa-search mr-2"></i>*#
<input type="date" name="dateInf" class="title__input form-control" style="border: 1px solid #ced4da; padding-left: 10px;" />
</div>
</div>
<div class="col-lg-3">
<div class="date mb-4">
#*<i class="fas fa-search mr-2"></i>*#
<input type="date" name="dateSup" class="title__input form-control" style=" border: 1px solid #ced4da;
padding-left: 10px;
" />
</div>
</div>
<div class="col-lg-3">
<div class="level">
#Html.DropDownList("Levels", ViewBag.Levels as SelectList, "Level", new { #class = "form-control" })
</div>
</div>
</div>
<div class="search">
<input type="submit" value="Search" class="text-white text-decoration-none btn btn-primary search__button" />
#*#Html.ActionLink("Search", "Index", "Announcement", null, new { #class = "text-white text-decoration-none btn btn-primary search__button" })*#
</div>
}
<!--list of all jobs searched for-->
<div class="container mt-5">
#{
if (!Model.Any())
{
<p class="text-center p-3 text-secondary">No job found with the chosen critiria</p>
}
else
{
<p class="text-secondary">#ViewBag.TotalResults job results found</p>
foreach (var item in Model)
{
<div class="row">
<div class="col-lg-7">
<div class="jobs">
#using (Html.BeginForm("Apply", "Application", new { idUser = User.Identity.GetUserId(), idAnnouncement = item.AnnouncementID }, FormMethod.Post, new { #class = "w-100 AnnonceForm" }))
{
<div class="job">
<div class="job__header d-flex align-items-center justify-content-between flex-wrap mb-0">
<h5 class="job__title">#item.Title</h5>
<h2 class="job__city">#item.Location</h2>
</div>
<h5 class="job__datetime">Posted in #item.PublicationDate.ToString("dd/mm/yyyy")</h5>
<h5 class="job__company-name mb-4">By #item.Company.Name</h5>
<div class="job__actions d-flex align-items-center">
<p class="job__apply my-0 mr-2">
#Html.ActionLink("More details", "AnnouncementDetails", "Application", new { idAnnouncement = item.AnnouncementID }, new { #class = "btn btn-primary" })
</p>
#if (!User.IsInRole("Company"))
{
<input type="submit" value="Apply Now" class="btn btn-outline-primary submit-btn">
}
</div>
</div>
}
</div>
</div>
<div class="col-lg-5"></div>
</div>
}
}
}
</div>
#section AnnouncementIndex {
<link href="#Url.Content("~/Content/Home.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/Announcement/AnnouncementIndex.css")" rel="stylesheet" type="text/css" />
}
#section Scripts{
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script>
let submitButtons = document.querySelectorAll(".submit-btn");
for (let i = 0; i < submitForms.length; i++) {
submitButtons[i].addEventListener("submit", e => {
e.preventDefault();
var el = this.parentElement;
while (el.className != 'AnnonceForm') {
el = el.parentElement;
}
//el is now your parent
let action = el.attr("action");
$.ajax({
method: "POST",
url: action,
data: {},
dataType: "json",
success: function (result) {
console.log("entered success block");
if (result.EnableSuccess) {
swal(
result.SuccessTitle,
result.SuccessMsg,
'success'
)
} else {
swal(
result.ErrorTitle,
result.ErrorMsg,
'warning'
)
}
},
error: function (err) {
console.log(err);
}
})
return false;
})
}
</script>
}
BUT, for some reason, I get this plain JSON result instead of actually returning to the success function in the AJAX call.
I am working on a form validator class in JavaScript.
First, I check (make sure) that all required fields are filled. If they are, I validate the email format:
class FormValidator {
constructor() {
this.hasErrors = false;
this.emptyRequired = [];
this.errorMsg = "";
this.formToValidate = document.querySelector("form");
this.submitButton = this.formToValidate.querySelector("input[type=submit]");
}
appendErrorMessage(){
const errorEl = `<span class="error-message">${this.errorMsg}</span>`;
this.emptyRequired.forEach((field) => {
let parentEl = field.parentElement;
if(this.hasErrors == true && parentEl.querySelectorAll('.error-message').length == 0) {
field.insertAdjacentHTML('afterend', errorEl);
}
});
}
validateEmail() {
this.hasErrors = false;
const re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
const emailFiled = this.formToValidate.querySelector('input[type=email]');
if (this.emptyRequired.length == 0) {
const action = re.test(emailFiled) ? 'remove' : 'add';
emailFiled.classList[action]('is-invalid');
this.hasErrors = re.test(emailFiled) ? false : true;
this.errorMsg = "Please provide a valid email";
this.appendErrorMessage();
}
}
validateRequired() {
this.hasErrors = false;
this.emptyRequired = [];
const requiredFields = this.formToValidate.querySelectorAll('*[required]');
requiredFields.forEach((field) => {
// Make sure all required fields have values
// Before doing other validations
if(!field.value) {
this.hasErrors = true;
this.emptyRequired.push(field);
this.errorMsg = "This field is required";
this.appendErrorMessage();
}
const action = field.value ? 'remove' : 'add';
field.classList[action]('is-invalid');
});
}
validateForm() {
this.validateRequired();
this.validateEmail();
console.log(this.errorMsg);
}
submitForm(e) {
e.preventDefault();
this.validateForm();
}
init() {
this.formToValidate.addEventListener('submit', e => this.submitForm(e));
}
}
const formValidator = new FormValidator();
formValidator.init();
.form-group {
position: relative;
}
.error-message {
margin: 0;
position: absolute;
right: 5px;
bottom: -13px;
color: #a94442;
font-size: 11px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<div class="card my-3">
<div class="card-header">Contact us</div>
<div class="card-body">
<form action="/" novalidate>
<div class="form-group">
<input type="text" name="name" class="form-control" placeholder="Your Name" value="" required />
</div>
<div class="form-group">
<input type="email" name="email" class="form-control" placeholder="Your Email" value="" required />
</div>
<div class="form-group">
<input type="text" name="phone" class="form-control" placeholder="Your Phone Number" value="" required />
</div>
<div class="form-group">
<textarea name="message" class="form-control" placeholder="Your Message"></textarea>
</div>
<div class="form-group mb-0">
<input type="submit" name="btnSubmit" class="btn btn-success btn-block" value="Send Message" />
</div>
</form>
</div>
</div>
</div>
The problem
I filled all the form fields, including the email. The email I provided is invalid.
For a reason I have not been able to figure out, the message Please provide a valid email is never appended to the <div class="form-group">.
I have a simple query submission form with name, email and query fields and a component with a controller function having the submit function to submit the form.
I am using ng-submit directive in the <form></form> tag to submit the user input and display a success message on submission.
below is the code for the respective files.
contact.html
<div ngController="contactController as vm">
<div class="heading text-center">
<h1>Contact Us</h1>
</div>
<div>
<form class="needs-validation" id="contactForm" novalidate method="post" name="vm.contactForm" ng-submit="saveform()">
<div class="form-group row">
<label for="validationTooltip01" class="col-sm-2 col-form-label">Name</label>
<div class="input-group">
<input type="text" class="form-control" id="validationTooltipName" placeholder="Name" ng-model="vm.name" required>
<div class="invalid-tooltip">
Please enter your full name.
</div>
</div>
</div>
<div class="form-group row">
<label for="validationTooltipEmail" class="col-sm-2 col-form-label">Email</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="validationTooltipUsernamePrepend">#</span>
</div>
<input type="email" class="form-control" id="validationTooltipEmail" placeholder="Email"
aria-describedby="validationTooltipUsernamePrepend" ng-model="vm.email" required>
<div class="invalid-tooltip">
Please choose a valid email.
</div>
</div>
</div>
<div class="form-group row">
<label for="validationTooltip03" class="col-sm-2 col-form-label">Query</label>
<div class="input-group">
<input type="text" class="form-control" id="validationTooltipQuery" ng-model="vm.query" placeholder="Query" required>
<div class="invalid-tooltip">
Please write your Query.
</div>
</div>
</div>
<div class="btn-group offset-md-5">
<button class="btn btn-primary" type="submit">Submit</button>
<button class="btn btn-default" type="button" id="homebtn" ng-click="navigate ('home')">Home</button>
</div>
</form>
<span data-ng-bind="Message" ng-hide="hideMessage" class="sucessMsg"></span>
</div>
</div>
contact.component.js
angular.module('myApp')
.component('contactComponent', {
restrict: 'E',
$scope:{},
templateUrl:'contact/contact.html',
controller: contactController,
controllerAs: 'vm',
factory:'userService',
$rootscope:{}
});
function contactController($scope, $state,userService,$rootScope) {
var vm = this;
$scope.navigate = function(home){
$state.go(home)
};
$scope.saveform = function(){
$scope.name= vm.name;
$scope.email= vm.email;
$scope.query= vm.email;
$scope.hideMessage = false;
$scope.Message = "Your query has been successfully submitted."
};
$scope.user = userService;
};
//localStorage code
function userService($rootScope) {
var service = {
model: {
name: '',
email: '',
query:''
},
SaveState: function () {
sessionStorage.userService = angular.toJson(service.model);
},
RestoreState: function () {
service.model = angular.fromJson(sessionStorage.userService);
}
}
$rootScope.$on("savestate", service.SaveState);
$rootScope.$on("restorestate", service.RestoreState);
return service;
$rootScope.$on("$routeChangeStart", function (event, next, current) {
if (sessionStorage.restorestate == "true") {
$rootScope.$broadcast('restorestate'); //let everything know we need to restore state
sessionStorage.restorestate = false;
}
});
//let everthing know that we need to save state now.
window.onbeforeunload = function (event) {
$rootScope.$broadcast('savestate');
};
};
UPDATE: On Submit, When I check the response in network tab in dev tools, I do not see the submitted values. All I see is the markup.
In your template, the name of the method is saveform:
ng-submit="saveform()"
But in your controller, it's save:
$scope.save = function() { ... }
Rename it to saveform:
$scope.saveform = function() { ... }
I am attempting to have the user inputs( first name, last name, contract number, amount) pass to payment.php and then be sent via $result = Braintree_Transaction::sale but payment_method_nonce is the only thing that passes to payment.php. When test payment.php with <?php print_r($_POST); ?> I only receive Array ( [payment_method_nonce] => 9ce4f24f-9746-076c-760b-d30d18a3cdf5 ) Thanks in advance Here is my code:
HTML
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default bootstrap-basic">
<div class="panel-heading">
<h3 class="panel-title">Enter Payment Details</h3>
</div>
<form class="panel-body" id="paymentportal" action="payment.php" method="post">
<div class="row">
<div class="form-group col-sm-6">
<label class="control-label">First Name</label>
<!-- Hosted Fields div container -->
<input type="text" placeholder="John" class="form-control" id="first-name">
</div>
<div class="form-group col-sm-6">
<label class="control-label">Last Name</label>
<!-- Hosted Fields div container -->
<input type="text" placeholder="Doe" class="form-control" id="last-name">
</div>
</div>
<div class="row">
<div class="form-group col-sm-6">
<label class="control-label">Contract Number</label>
<!-- Hosted Fields div container -->
<input type="text" placeholder="1462" class="form-control" id="order-number">
</div>
<div class="form-group col-sm-6">
<label class="control-label">Amount</label>
<!-- Hosted Fields div container -->
<input type="text" placeholder="$1234.56" class="form-control" id="amount">
</div>
</div>
<div class="row">
<div class="form-group col-sm-8">
<label class="control-label">Card Number</label>
<!-- Hosted Fields div container -->
<div class="form-control" id="card-number"></div>
<span class="helper-text"></span>
</div>
<div class="form-group col-sm-4">
<div class="row">
<label class="control-label col-xs-12">Expiration Date</label>
<div class="col-xs-6">
<!-- Hosted Fields div container -->
<div class="form-control" id="expiration-month"></div>
</div>
<div class="col-xs-6">
<!-- Hosted Fields div container -->
<div class="form-control" id="expiration-year"></div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-sm-6">
<label class="control-label">Security Code</label>
<!-- Hosted Fields div container -->
<div class="form-control" id="cvv"></div>
</div>
<div class="form-group col-sm-6">
<label class="control-label">Zipcode</label>
<!-- Hosted Fields div container -->
<div class="form-control" id="postal-code"></div>
</div>
</div>
<input type="hidden" name="payment_method_nonce" id="payment_method_nonce">
<button value="btnSubmit" id="btnSubmit" class="btn-box center-block">Pay with <span id="card-type">Card</span></button>
</form>
</div>
</div>
JS
var form = document.getElementById('paymentportal');
braintree.client.create({
authorization: 'sandbox_authorization'
}, function (err, clientInstance) {
if (err) {
console.error(err);
return;
}
braintree.hostedFields.create({
client: clientInstance,
styles: {
'input': {
'font-size': '14px',
'font-family': 'helvetica, tahoma, calibri, sans-serif',
'color': '#3a3a3a'
},
':focus': {
'color': 'black'
}
},
fields: {
number: {
selector: '#card-number',
placeholder: '4111 1111 1111 1111'
},
cvv: {
selector: '#cvv',
placeholder: '123'
},
expirationMonth: {
selector: '#expiration-month',
placeholder: 'MM'
},
expirationYear: {
selector: '#expiration-year',
placeholder: 'YY'
},
postalCode: {
selector: '#postal-code',
placeholder: '90210'
}
}
}, function (err, hostedFieldsInstance) {
if (err) {
console.error(err);
return;
}
hostedFieldsInstance.on('validityChange', function (event) {
var field = event.fields[event.emittedBy];
if (field.isValid) {
if (event.emittedBy === 'expirationMonth' || event.emittedBy === 'expirationYear') {
if (!event.fields.expirationMonth.isValid || !event.fields.expirationYear.isValid) {
return;
}
} else if (event.emittedBy === 'number') {
$('#card-number').next('span').text('');
}
// Remove any previously applied error or warning classes
$(field.container).parents('.form-group').removeClass('has-warning');
$(field.container).parents('.form-group').removeClass('has-success');
// Apply styling for a valid field
$(field.container).parents('.form-group').addClass('has-success');
} else if (field.isPotentiallyValid) {
// Remove styling from potentially valid fields
$(field.container).parents('.form-group').removeClass('has-warning');
$(field.container).parents('.form-group').removeClass('has-success');
if (event.emittedBy === 'number') {
$('#card-number').next('span').text('');
}
} else {
// Add styling to invalid fields
$(field.container).parents('.form-group').addClass('has-warning');
// Add helper text for an invalid card number
if (event.emittedBy === 'number') {
$('#card-number').next('span').text('Looks like this card number has an error.');
}
}
});
hostedFieldsInstance.on('cardTypeChange', function (event) {
// Handle a field's change, such as a change in validity or credit card type
if (event.cards.length === 1) {
$('#card-type').text(event.cards[0].niceType);
} else {
$('#card-type').text('Card');
}
});
$('.panel-body').submit(function (event) {
event.preventDefault();
hostedFieldsInstance.tokenize(function (err, payload) {
if (err) {
console.error(err);
return;
}
document.querySelector('input[name="payment_method_nonce"]').value = payload.nonce;
// This is where you would submit payload.nonce to your server
form.submit();
});
});
});
});
PHP
<?php
$result = Braintree_Transaction::sale([
'amount' => $_POST['amount'],
'orderId' => $_POST['order-number'],
'paymentMethodNonce' => $_POST['payment_method_nonce'],
'customer' => [
'firstName' => $_POST['first-name'],
'lastName' => $_POST['last-name'],
],
'options' => [
'submitForSettlement' => true
]
]);
if ($result->success === true){
}else
{
print_r($result->errors);
die();
}
?>
Full disclosure: I work at Braintree. If you have any further questions, feel free to contact
support.
Remember when you collect form data on your server, you need to reference those inputs by their name attribute. Once you add the respective name values to each of these inputs, it should work as expected.
For example, your first name input;
<input type="text" placeholder="John" class="form-control" id="first-name" name="first-name">
I have an event on google tag manager that should fire when a form is submitted successfully. The form is an embedded code from Cognito Forms. The page is hosted in squarespace. Using Google Tag Manager preview I can see all conditions are met once submissions with the exception of the function below, which should be "true" on successful submission, but for some reason it is false even if I submit form successfully.
What could be going wrong? This is the contact us form and below the function. Thanks a lot.
function areAllFieldsFilled(){
var requiredFields = document.getElementsByClassName('cognito')[0].getElementsByTagName('form')[0].getElementsByTagName('input');
var questions = document.getElementsByClassName('cognito')[0].getElementsByTagName('form')[0].getElementsByTagName('textarea')[0];
var check = 0;
if (questions == '') {
check++;
} else{
for (var i = 0; i < 3; i++) {
if (requiredFields[i].value == '') {
check++;
break;
}
}
}
if (check == 0) {
return true;
} else {
return false;
}
}
I inspected your form and it looks like there are 2 reasons why you are returning false for a filled in form.
As noted by James in the comments, you need to do questions.value == '' and not questions == ''
There is a hidden <input /> tag in the form you probably didn't notice. The value of that input is always empty string because it doesn't have a value. To quickly fix this, you can start your loop at 1. Side Note: the length of your loop should be requiredFields.length -1 (since we are now starting at 1 instead of 0) instead of hard coding 3
Here is a working example
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementById("c-submit-button").addEventListener("click", areAllFieldsFilled);
});
function areAllFieldsFilled(event) {
event.preventDefault(); // For testing, REMOVE THIS
var requiredFields = document.getElementsByTagName('form')[0].getElementsByTagName('input');
var questions = document.getElementsByTagName('form')[0].getElementsByTagName('textarea')[0];
var check = 0;
if (questions.value == '') {
console.log("questions was empty");
check++;
} else {
for (var i = 1; i < requiredFields.length - 1; i++) {
if (requiredFields[i].value == '') {
check++;
break;
}
}
}
console.log(`check count is ${check}`);
if (check == 0) {
console.log("Returning True");
return true;
} else {
console.log("Returning False");
return false;
}
// or replace the above 7 lines with return check == 0
}
<form lpformnum="1">
<div class="c-forms-form" tabindex="0">
<div class="c-editor" style="display:none;">
<input type="text" class="c-forms-form-style" style=" background-repeat: no-repeat; background-attachment: scroll; background-size: 16px 18px; background-position: 98% 50%;">
</div>
<div class="c-forms-form-body">
<div class="c-forms-template" sys:attach="dataview" dataview:data="{binding entry, source={{ Cognito.Forms.model }} }">
<div class="c-forms-form-main c-span-24 c-sml-span-12">
<div class="c-section c-col-1 c-sml-col-1 c-span-24 c-sml-span-12" data-field="Section">
<div class="">
<div class="c-section c-col-1 c-sml-col-1 c-span-24 c-sml-span-12" data-field="Section">
<div class="">
<div class="c-name c-field c-col-1 c-sml-col-1 c-span-24 c-sml-span-12 c-required" data-field="Name">
<div class="c-label">
<label>Name</label>
</div>
<div>
<div class="c-offscreen">
<label for="c-0-12">First</label>
</div>
<div class="c-editor c-span-1" style="width: 50%; float: left;">
<input type="text" id="c-0-12" placeholder="First">
</div>
<div class="c-offscreen">
<label for="c-1-12">Last</label>
</div>
<div class="c-editor c-span-1" style="width: 50%; float: left;">
<input type="text" id="c-1-12" placeholder="Last">
</div>
</div>
<div class="c-validation">First and Last are required.</div>
</div>
<div class="c-email c-field c-col-1 c-sml-col-1 c-span-24 c-sml-span-12 c-required" data-field="PreferredEmailAddress">
<div class="c-label">
<label for="c-3-11">Preferred Email Address</label>
</div>
<div class="c-editor">
<input type="text" id="c-3-11">
</div>
<div class="c-validation">Preferred Email Address is required.</div>
</div>
<div class="c-phone c-phone-international c-field c-col-1 c-sml-col-1 c-span-12 c-sml-span-12 c-required" data-field="Phone">
<div class="c-label">
<label for="c-4-10">Phone</label>
</div>
<div class="c-editor">
<input type="text" id="c-4-10">
</div>
<div class="c-validation">Phone is required.</div>
</div>
<div class="c-yesno-radiobuttons c-field c-col-13 c-sml-col-1 c-span-12 c-sml-span-12" data-field="WouldYouLikeForUsToCallYou">
<legend class="c-label">Would you like for us to call you?</legend>
<div class="c-editor c-columns-0">
<label class="c-yesno-radio" for="c-5-8">
<input type="radio" name="group7" id="c-5-8" checked="checked"><span>Yes</span></label>
<label class="c-yesno-radio" for="c-5-9">
<input type="radio" name="group7" id="c-5-9"><span>No</span></label>
</div>
<div class="c-validation"></div>
</div>
<div class="c-text-multiplelines c-field c-col-1 c-sml-col-1 c-span-12 c-sml-span-12 c-required" data-field="Questions">
<div class="c-label">
<label for="c-6-6">Questions:</label>
</div>
<div class="c-editor">
<textarea id="c-6-6" type="text" height=""></textarea>
</div>
<div class="c-validation">Questions: is required.</div>
</div>
</div>
<div class="c-validation"></div>
</div>
</div>
<div class="c-validation"></div>
</div>
</div>
</div>
<div id="c-recaptcha-div"></div>
<div class="c-forms-error">
<div class="c-validation"></div>
</div>
<div class="c-button-section">
<div class="c-action">
<button class="c-button" id="c-submit-button">Submit</button>
</div>
</div>
</div>
<div class="c-forms-confirmation">
<div class="c-forms-confirmation-message c-html" sys:attach="dataview" dataview:data="{binding entry, source={{ Cognito.Forms.model }} }"><span><p><strong>Thank you for reaching out!</strong></p> <p>We look forward to being in touch with you soon.</p></span></div>
</div>
</div>
</form>
Some notes:
Using a more selective selector would be a more concrete approach.