Save data from form - javascript

I want to save the data that I get from my form (html).
I have same fileds in my form and I want to send them from html page to node.js page and from there to mongoDB (mlab) database.
In my node page I use angular to save the data that I gets form user.
I'm using ng-controller to connect to js page, and using ng-model to hold the data that I get in input label.
My problem is that I cant save the data in mongoDB?
Thanks,
html:
<body ng-controller="addController">
<h1 class="text-center">Add Activity</h1>
<form class="form-group" ng-submit="createActivity()">
<div class="form-group">
<div class="col-sm-10">
<label for="inputEmail3" class="col-sm-2 control-label">Title:</label>
<input class="form-control" type="text" placeholder="Title" ng-model="title"></input>
</div>
<div class="col-sm-10">
<label for="inputEmail3" class="col-sm-2 control-label">Age:</label>
<input class="form-control" id="inputEmail3" type="number" placeholder="Age" ng-model="age" min="0" max="16"></input>
</div>
<div class="col-sm-10">
<label for="inputEmail3" class="col-sm-2 control-label">Description:</label>
<textarea class="form-control" id="inputEmail3" type="text" placeholder="Description" ng-model="description"></textarea>
<br>
</div>
<div class="col-sm-10">
<label for="inputEmail3" class="col-sm-2 control-label">Themes:</label>
<input type="radio" name="themes" value="frozen" ng-model="theme">frozen
<input type="radio" name="themes" value="minions" ng-model="theme">minions
<input type="radio" name="themes" value="heroes" ng-model="theme">heroes
<input type="radio" name="themes" value="princess" ng-model="theme">princess
<input type="radio" name="themes" value="piraets" ng-model="theme">piraets
<input type="radio" name="themes" value="none" ng-model="theme">none
<br>
</div>
<div class="col-sm-10">
<br>
<input type="file" name="upload" ng-model="image"></input>
</div>
<div class="col-sm-10">
<br>
<input type="submit" class="btn btn-default" name="send"></input>
</div>
</div>
</form>
js:
var addActivityApp = angular.module('addActivityApp',['$scope','$resource']);
var Activity = $resource('/activities');
var activity = new Activity();
$scope.createActivity=function () {
var activity = new Activity();
activity.title = $scope.title;
activity.age = $scope.age;
activity.description = $scope.description;
activity.theme = $scope.theme;
activity.$save(function (result) {
$scope.activities.push(result);
$scope.title = '';
$scope.age = '';
$scope.description = '';
$scope.theme = '';
});
});
addActivityApp.controller('addController',function($scope) {
$scope.addController = model;
});

You can try the below code. check if you using the same below code on your server side.
app.post('yourserverurl', function(req, res) {
console.log(req.body) //Here all form data will display
var InsertData = req.body;
db.collection('restaurants').insertOne(InsertData,function(err, result) {
assert.equal(err, null);
console.log("Inserted a document into the collection.");
callback();
});
});
if you share the whole code which you have written in server side, so i can simplify it more

Related

Laravel stripe and cashier no such payment method

I am using Laravel 7 and i am integratng stripe with cashier and i am facing issue
No such PaymentMethod: 'tok_1HBxFdEft5GkDC4v7ZnPgW5Y'
I am using custom checkout forms Html code is
<form class="rt-formtheme rt-paymentmethodform" method="POST" action="{{route('subscripe.process')}}" id="subscribe-form">
#csrf
<div class="div-stripe-errors col-12" style="margin-top: 30px;"></div>
<fieldset>
<legend>Choose your card</legend>
<!-- <div class="form-group">
<button type="submit" class="rt-btn rt-savebtn">Save</button>
</div> -->
<div class="form-group">
<span class="rt-radio">
<input type="radio" name="radiobutton" id="visa">
<label for="visa"><img src="{{asset('images/visa.png')}}" alt=""></label>
</span>
</div>
<div class="form-group">
<span class="rt-radio">
<input type="radio" name="radiobutton" id="american-express">
<label for="american-express"><img src="{{asset('images/american-express.png')}}" alt=""></label>
</span>
</div>
<div class="form-group">
<label>Card Number</label>
<input type="text" name="cardnumber" class="form-control" placeholder="1234 5678 9012 3456" data-stripe="number">
</div>
<div class="rt-twocols">
<div class="form-group">
<div class="rt-twoinputfieldholder">
<div class="rt-twoinputfieldbox">
<label>Expiry Month</label>
<input type="text" name="expirymonth" class="form-control" placeholder="MM" data-stripe="exp-month">
</div>
<div class="rt-twoinputfieldbox">
<label>Expiry Year</label>
<input type="text" name="expiryyear" class="form-control" placeholder="YY" data-stripe="exp-year">
</div>
</div>
</div>
<div class="form-group">
<label>CVC</label>
<input type="text" name="cvv" class="form-control" placeholder="123" data-stripe="cvc">
</div>
</div>
<div class="form-group margin-zero rt-savecarddetailbox">
<span class="rt-checkbox">
<input type="checkbox" name="savecarddetail" id="savecarddetail">
<label for="savecarddetail">Save Card Details</label>
</span>
<button type="submit" class="rt-btn float-right">Checkout</button>
</div>
</fieldset>
</form>
and js code is
<script src="https://js.stripe.com/v2/"></script>
<script>
Stripe.setPublishableKey('{{ env("STRIPE_KEY") }}');
$(document).ready(function(){
$('#subscribe-form').submit(function(e){
var form = $(this);
form.find('button').prop('disabled', true);
Stripe.card.createToken(form, function(status, response) {
if (response.error) {
form.find('.div-stripe-errors').text(response.error.message).addClass('alert alert-danger');
form.find('button').prop('disabled', false);
} else {
// append the token to the form
form.append($('<input type="hidden" name="cc_token">').val(response.id));
// debugger
// submit the form
form.get(0).submit();
}
});
e.preventDefault();
});
});
Route is
Route::post('/subscribe_process', 'Dashboard\CheckoutController#subscribeProcess')->name('subscripe.process');
and controller method is
public function subscribeProcess(Request $request)
{
try{
$cc_token = $request->cc_token;
$user = Auth::user();
$user->newSubscription('Main','Monthly')->create($cc_token);
alert()->success('User Updated Successfully', 'Success');
return \redirect()->back();
}catch(\Exception $ex){
return $ex->getMessage();
}
}
and i also create plan on stripe dashboard
when i create a subscription it show error No such payment method i am new in stripe kindly help me
"No such..." errors are usually caused by either a mismatch in API keys (e.g. using a mixture of your test plus live keys) or by trying to access objects that exist on a different account (e.g. trying to perform an operation from your platform account on an object that was created on a connected account).

Onsubmit not working

I have this form and I tried to make a "onsubmit" that when I click submit it checks if the "email" is = to "cemail" and if username was taken before or not i got this so far
<form class="form-horizontal" action="#" method="post" onsubmit="return ValidationEvent()">
<fieldset>
<legend>SIGN UP! <i class="fa fa-pencil pull-right"></i></legend>
<div class="form-group">
<div class="col-sm-6">
<input type="text" id="firstName" placeholder="First Name" class="form-control" name="firstname" autofocus required>
</div>
<div class="col-sm-6">
<input type="text" id="lastname" placeholder="Last Name" class="form-control" name="lastname" autofocus required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="email" placeholder="Email" name="email" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="cemail" placeholder=" Re-enter Email" name="cemail" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="username" placeholder=" Username" name="username" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="password" id="password" placeholder="Password" name="password" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="datepicker" placeholder= "DOB" name="birthday" class="form-control" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-1"></label>
<div class="col-sm-8">
<div class="row">
<label class="radio-inline">
<input type="radio" id="radio" value="Female" name= "gender" required>Female
</label>
<label class="radio-inline">
<input type="radio" id="radio" value="Male" name= "gender">Male
</label>
</div>
</div>
</div> <!-- /.form-group -->
<div class="form-group">
<div class="col-sm-4 col-sm-offset-3">
<button type="submit" class="btn btn-primary btn-block">Register</button>
</div>
</div>
</form>
Javascript code:
<script>
function ValidationEvent() {
var email = document.getElementById("email").value;
var username = document.getElementById("username").value;
var cemail = document.getElementById("cemail").value;
// Conditions
if (email.match != cemail.match) {
alert("Your email doesn't match!");
}
if(mysqli_num_rows($result) != 0)
{
alert("Username already taken!");
}
else {
alert("Thank you");
}
}
</script>
Am I approaching the function in the wrong way is there another easier way and is it okay i put an sql statement in my java script ?
First, don't use inline HTML event handling attributes (like "onsubmit") as they create "spaghetti code", anonymous global event handling wrapper functions and don't conform to the modern W3C DOM Event handling standard.
Second, your .php results have to be gotten from somewhere. You'll need to put a call into that file for its results before you can use them.
Next, you were using the .match() string method incorrectly to compare the emails against each other. All you really need to do is compare the values entered into the email fields (it's also a good idea to call .trim() on form values to strip out any leading or trailing spaces that might have been inadvertently added).
Once you restructure your code to use standards, the JavaScript will change as follows (FYI: This won't work in the Stack Overflow snippet environment because form submissions are blocked, so you can see a working version here):
// When the DOM is loaded:
window.addEventListener("DOMContentLoaded", function(){
// Get references to the DOM elements you will need:
var frm = document.getElementById("frm");
// Don't set variables to the values of DOM elements,
// set them to the DOM elements themselves so you can
// go back and get whatever properties you like without
// having to scan the DOM for them again
var email = document.getElementById("email");
var username = document.getElementById("username");
var cemail = document.getElementById("cemail");
// Set up a submit event handler for the form
frm.addEventListener("submit", validationEvent);
// All DOM event handling funcitons receive an argument
// that references the event they are responding to.
// We need that reference if we want to cancel the event
function validationEvent(evt) {
// Conditions
if (email.value.trim() !== cemail.value.trim()) {
alert("Your email doesn't match!");
// Cancel the form submit event
evt.preventDefault();
evt.stopPropagation();
return;
}
// You need to have already gotten the "mysqli_num_rows($result)" value
// from your .php file and saved it to a variable that you can then check
// here against "!=0"
if(mysqli_num_rows($result) != 0) {
alert("Username already taken!");
// Cancel the form submit event
evt.preventDefault();
evt.stopPropagation();
} else {
alert("Thank you");
}
}
});
<form class="form-horizontal" id="frm" action="#" method="post">
<fieldset>
<legend>SIGN UP! <i class="fa fa-pencil pull-right"></i></legend>
<div class="form-group">
<div class="col-sm-6">
<input type="text" id="firstName" placeholder="First Name" class="form-control" name="firstname" autofocus required>
</div>
<div class="col-sm-6">
<input type="text" id="lastname" placeholder="Last Name" class="form-control" name="lastname" autofocus required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="email" placeholder="Email" name="email" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="cemail" placeholder=" Re-enter Email" name="cemail" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="username" placeholder=" Username" name="username" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="password" id="password" placeholder="Password" name="password" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="datepicker" placeholder= "DOB" name="birthday" class="form-control" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-1"></label>
<div class="col-sm-8">
<div class="row">
<label class="radio-inline">
<input type="radio" id="radio" value="Female" name= "gender" required>Female
</label>
<label class="radio-inline">
<input type="radio" id="radio" value="Male" name= "gender">Male
</label>
</div>
</div>
</div> <!-- /.form-group -->
<div class="form-group">
<div class="col-sm-4 col-sm-offset-3">
<button type="submit" class="btn btn-primary btn-block">Register</button>
</div>
</div>
</form>
For checking the emails with email & cemail use
email.localeCompare(cemail)
This will check the string comparison betwwen two emails
And for mysqli_num_rows , is not defined any where in javascript, so we will get the undefined error in console, so need to write a different funnction with that name.
First give a name and an action to your form
<form class="form-horizontal" id="myform" action="chkValues.php" method="post" >
....
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="email" placeholder="Email" name="email" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="cemail" placeholder=" Re-enter Email" name="cemail" class="form-control" required>
</div>
</div>
....
</form>
Then put this script at the bottom
<script>
$('#myForm').on("sumbit", function(){
// cancel the original sending
event.preventDefault();
$.ajax({
var form = $(this);
var action = form.attr("action"),
method = form.attr("method"),
data = form.serialize();
})
.done: function(data) // is called wehn the call was okay
{
if( data.substr(0, 5) == "Error"){
alert(data); // sent the sting of the "error message" begining with "Error"
}else{
top.location.href = data; // sent the sting of the "success page" when all was okay and data are saved in the database
}
}
.fail(function() {
alert( "Error: Getting data from Server" );
})
});
</script>
in the php file check the values an return an error if something went wrong.
<?php
if(!isset($_POST['email']) || !isset($_POST['cemail'])){
die("Error: Please fill out both email fields.");
if($_POST['email'] != $_POST['cemail'] ){
die("Error: The Email adresses do not match.");
}
here do what you want to do with the data.
when finish just send the new url
echo "success.html";
}
?>

angularjs - form with ng-repeat inside it error on submitting

I have the following form : two text inputs then an ng-repeat with a text and radio inside.
<form class="form-horizontal" id="myForm" name="myForm">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Company Name</label>
<div class="col-sm-10">
<input type="text" name="cname" ng-model="company.name" class="form-control" required></input>
</div>
</div>
<div class="form-group">
<label for="category" class="col-sm-2 control-label">HQ</label>
<div class="col-sm-10">
<select ng-model="company.hq" ng-options="hq as hq.name for hq in hqs" required>
<option></option>
</select>
</div>
</div>
<div class="form-group" ng-repeat="item in getR(4) track by $index">
<label for="name" class="col-sm-2 control-label">Top pick {{$index+1}}</label>
<div class="col-sm-10">
<input type="text" name="quizsize" ng-model="company.product[$index]" class="form-control" required></input>
<label><input type="radio" name="test" ng-model="company.radioValue" value="{{$index+1}}"/> Choose</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" value="submit" class="btn btn-primary" ng-click="addCompany(company)"></button>
<button type="btn" value="cancel" class="btn btn-danger" ng-click="cancelBtn()">Cancel</button>
</div>
</div>
</form>
addCompany method from the controller :
$scope.addCompany = function(company)
{
console.log(company.radioValue);
$http.post('http://localhost/api/index.php/Test/companies', company)
.success(function(data)
{
$scope.companies.push(data[0]);
})
.error(function(err)
{
})
};
And the method to for the inputs ng-repeat:
$scope.getR = function(n)
{
return Array(n);
}
When I submit it:
If I start by adding company name/hq then all is good, but
If I start by first clicking on a radio button then when I send the form I get an undefined radioValue error.
use ng-value instead of value to be sure the model is ready to be bound to
<input type="radio" ng-value="($index + 1)" ng-model="company.radioValue">
https://docs.angularjs.org/api/ng/directive/ngValue

Controller as vm with ng-click

I am trying to follow John Papa's Angular Style Guide however i cannot get the model data of input file with ngClick.
When i try with $scope everything works just fine.
Here is the Demo on Plnkr.
Glad for your help.
In the ng-model instead of assigning directly to vm, assign it to vm.data and pass vm.data as argument to ng-click like data-ng-click="vm.saveEvent(vm.data)"
<form>
<fieldset>
<div class="form-group">
<label for="eventName">Event Name:</label>
<input id="eventName" type="text" data-ng-model="vm.data.name" placeholder="Name of your event"/>
</div>
<div class="form-group">
<label for="eventDate">Event Date:</label>
<input id="eventDate" type="text" data-ng-model="vm.data.date" placeholder="format (mm/dd/yyyy)"/>
</div>
<div class="form-group">
<label for="eventTime">Event Time:</label>
<input id="eventTime" type="text" data-ng-model="vm.data.time" placeholder="Time of your event"/>
</div>
<div class="form-group">
<label for="eventLocation">Event Location:</label>
<input id="eventLocation" type="text" data-ng-model="vm.data.location.addresss" placeholder="Address of your event"/>
</div>
<div class="form-group">
<input id="eventCity" type="text" class="input-small" data-ng-model="vm.data.location.city" placeholder="City"/>
<input id="stateProvince" type="text" class="input-small" data-ng-model="vm.data.location.province" placeholder="Province"/>
</div>
<div class="form-group">
<label for="eventImageUrl">Image:</label>
<input id="eventImageUrl" type="text" class="input-xlarge" data-ng-model="vm.data.imageUrl" placeholder="Url of image"/>
</div>
</fieldset>
{{vm.data.name}}
<img data-ng-src="{{vm.data.imageUrl}}"/>
<br/>
<br/>
<div class="form-group">
<button type="submit" class="btn btn-primary" data-ng-click="vm.saveEvent(vm.data)">Save</button>
<button type="button" class="btn btn-default" data-ng-click="vm.cancelEvent(vm.data)">Cancel</button>
</div>
</form>
Controller:
eventsApp.controller('EditEventController',
function EditEventController() {
var vm = this;
this.data = {};
vm.saveEvent = saveEvent;
function saveEvent(event) {
window.alert("event" + event.name + ' saved');
console.log(vm.data);
}
//vm.saveEvent = function(event) {
// window.alert("event" + event.name + ' saved');
//};
}
);
http://plnkr.co/edit/AxdA7vc70aTw3RojofVY?p=preview
ng-click="vm.saveEvent(vm.data)" did not work for me with Angular 1.4.
My solution was to use the control variable name.
e.g. "LoginController as loginctrl" so <button ng-click="loginctrl.doLogin()">Login</button>
Then in my control I was able to use this for the doLogin function inside my LoginController:
/* #ngInject */
function LoginController() {
/*jshint validthis: true */
var vm = this;
vm.title = 'Login';
function doLogin() {
...
}

Reset form after submission in AngularJS

I'm having trouble resetting form fields after submitting in AngularJS (v1.1.3). Here's a snippet of what I'm trying to do:
HTML
<form name="addMemberForm">
<input name="name" type="text" placeholder="Jon Doe" ng-model="member.name" required/></td>
<a class="btn btn-primary" ng-click="createMember(member)" ng-disabled="addMemberForm.$invalid"><i class="icon-plus"></i></a>
</form>
JS
$scope.createMember = function(member) {
var membersService = new Members(member);
membersService.$create(function(member) {
$scope.members.push(member);
$scope.addMemberForm.reset(); //TypeError: Object #<FormController> has no method 'reset'
});
};
Is there another way to reset form elements?
Figured it out thanks to #tschiela's comment. I had to do this:
$scope.createMember = function(member) {
var membersService = new Members(member);
membersService.$create(function(member) {
$scope.members.push(member);
$scope.member = '';
});
};
Just Take default value of the form .
HTML form
<form novalidate id="paperForm" class="form-horizontal" name="formPaper">
<div class="form-group">
<label class="col-sm-3 control-label" for="name">
Name
</label>
<div class="col-sm-8">
<input type="text" id="name" placeholder="Please Enter Name" class="form-control" ng-model="paper.name" ng-name="name" required>
</div>
<label class="col-sm-3 control-label" for="name">
Department
</label>
<div class="col-sm-8">
<input type="text" id="department" placeholder="Please Enter Department" class="form-control" ng-model="paper.department" ng-name="department" required>
</div>
</div>
<button type="button" class="btn btn-default" ng-click="reset(paper)">Reset</button>
</form>
set reset code inside controller
var deafualtForm = {
name : '',
department : ''
}
$scope.reset= function(paper) {
$scope.paper = angular.copy(deafualtForm);
}

Categories

Resources