First week using Angular and I am now trying to post to a third party API.
I would like some help getting this form posting the data correctly, for extra points some comments and expectation on what line is doing what.
I am getting this error
ReferenceError: formData is not defined
at h.$scope.processForm (controller.js:116)
at angular.js:10567
at angular.js:18627
at h.$eval (angular.js:12412)
at h.$apply (angular.js:12510)
at HTMLFormElement.<anonymous> (angular.js:18626)
at angular.js:2780
at q (angular.js:330)
at HTMLFormElement.c (angular.js:2779)
The API I am posting to requires user_key 0000 and api_key 0000to be sent, although theses are not dynamic like the form fields so are always the same.
My current form
<form name="myForm" id="signup-form" class="col-sm-8 col-sm-offset-2" ng-click="postdata(Fname, Lname, email)">
<div class="form-group">
<label for="first-name">First Name*</label>
<input type="text" class="form-control col-sm-12" name="Fname" placeholder="Enter first name"
ng-model="formData.Fname"
ng-required="true">
<span ng-if="!myForm.Fname.$invalid" class="glyphicon glyphicon-ok " style="color: green" aria-hidden="true"></span>
</div>
<div class="form-group">
<label for="first-name">Last Name*</label>
<input type="text" class="form-control col-sm-12" name="Lname" placeholder="Enter last name"
ng-model="formData.Lname"
ng-required="true">
<span ng-if="!myForm.Lname.$invalid" class="glyphicon glyphicon-ok " style="color: green" aria-hidden="true"></span>
</div>
<div class="form-group">
<label for="first-name">Email*</label>
<input type="email" class="form-control col-sm-12" name="email" placeholder="Enter valid E-mail"
ng-model="formData.email"
ng-required="true">
<span ng-if="!myForm.email.$invalid" class="glyphicon glyphicon-ok " style="color: green" aria-hidden="true"></span>
</div>
<div class="form-group row">
<div class="col-xs-6 col-xs-offset-3">
<button ui-sref="form.select" class="btn btn-block btn-info"
ng-disabled="!myForm.$valid">
Next Section <span class="glyphicon glyphicon-circle-arrow-right"></span>
</button>
</div>
</div>
</form>
My controller
// submit button controller POST
// =============================================================================
.controller('formController', function ($scope, $http) {
$scope.Fname = null;
$scope.Lname = null;
$scope.email = null;
$scope.lblMsg = null;
$scope.processForm = function (Fname, Lname, email) {
var data = {
Fname: formData.Fname,
Lname: formData.Lname,
email: formData.email,
api_key: 0000,
user_key: 0000
};
//Call the services
$http.post('https://API/do/create', JSON.stringify(data)).then(function (response) {
if (response.data)
$scope.msg = "Post Data Submitted Successfully!";
}, function (response) {
$scope.msg = "Service not Exists";
$scope.statusval = response.status;
$scope.statustext = response.statusText;
$scope.headers = response.headers();
});
};
});
You should have some changes in your code.
1- Declare $scope.formData = {}
2- Remove
$scope.Fname = null;
$scope.Lname = null;
$scope.email = null;
$scope.lblMsg = null;
because you can access to them with $scope.formData object.
3- change formData.Fname to $scope.formData.Fname, and other similar to this
$scope.formData = {}; // declare in controller
var data = {
Fname: $scope.formData.Fname,
Lname: $scope.formData.Lname,
email: $scope.formData.email,
api_key: 0000,
user_key: 0000
};
4- you can pass formData object to function or don't pass it.If passing formData to function so use following
ng-click="postdata(formData)"
var data = {
Fname: formData.Fname,
Lname: formData.Lname,
email: formData.email,
Related
I have a contact form. On submission, it displays a success message and it should store that data to $localStorage.
But, Form data not is not submitting as I do not see submitted form data in response under network in dev tools and hence I am unable to save it to $localStorage.
below is the code for respective files.
link to plunker
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) {
var vm = this;
vm.saveform = function(){
var name= vm.name;
var email= vm.email;
var query= vm.query;
console.log(name);
console.log(email);
console.log(query);
$scope.hideMessage = false;
$scope.Message = "Your query has been successfully submitted.";
$scope.user = userService;
};
$scope.navigate = function(home){
$state.go(home)
};
};
//localStorage code
function userService(saveform) {
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');
};
};
There are no errors in console.
Referring to this documentation here, I am trying to hide my element if the mode in the controller function is verifyEmail. No success. Could somebody help to see why it doesn't work?
My HTML is like:
<div class="box-forgot" ng-controller="ResetPass">
<form class="form-forgot" name="resetpassword" ng-hide="mode == 'verifyEmail'">
<fieldset>
<legend>
Reset Password:
</legend>
<div class="form-group">
<span class="input-icon">
<input type="password" class="form-control" id="password" ng-model="user.password" name="password" placeholder="Password" required="">
<i class="fa fa-lock"></i> </span>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary pull-right" ng-click="resetMe()">
Reset
</button>
</div>
</fieldset>
</form>
</div>
And the corresponding controller is:
app.controller("ResetPass", ["$scope","firebase", "$location",
function ($scope,firebase, $location) {
$scope.resetMe = function () {
var newPassword = $scope.user.password;
var actionCode = $location.search().oobCode;
var mode = $location.search().mode;
firebase.auth().confirmPasswordReset(actionCode, newPassword)
.then(function (resp) {
console.log("reset pass, done");
$location.path('/login.signin');
}).catch(function (error) {
$scope.errMsg = true;
$scope.errorMessage = error.message;
});
}
}]);
Try to bind mode with $scope object instead of var
Instead of
var mode = $location.search().mode;
Do this
$scope.mode = $location.search().mode;
The variable you're trying to reference in your HTML is not visible because it's not in the controller's scope.
You have to change this:
var mode = $location.search().mode;
to this:
var mode = $scope.mode = $location.search().mode;
// or
$scope.mode = $location.search().mode;
I want to send form Data from my HTML/AngluarJS page by POST to the server (NodeJS), When submit I'm getting 400 (Bad request)
HTML Page that uses ng-submit:
<div class="container start" ng-controller="adminController">
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-body"><h1>Administration</h1>
<!-- form -->
<form class="form-signin" ng-submit="submit()" ng-controller="adminController">
<h2 class="form-signin-heading">Add new Bird</h2>
<select name= "tagType" id= "inputTag" class="form-control" placeholder="Tag Type" ng-modal="bird.tagType">
<option ng-repeat="tag in tags" value="{{option.id}}">{{tag.tagName}}</option>
</select><br/>
<button class="btn btn-primary" ng-click="addTag()">Add Tag</button>
<br/><br/>
<select name = "specie" id= "inputSpecie" class="form-control" placeholder="Specie Category" ng-modal="bird.specie">
<option ng-repeat="specie in species" value="{{option.id}}">{{specie.latinName}}</option>
</select>
<br/>
<button class="btn btn-primary" ng-click="addSpecie()">Add Specie</button>
<br/><br/>
<input type="text" id="inputSex" class="form-control" placeholder="Sex" ng-modal="bird.sex"/>
<br/><br/>
<input type="text" id="inputRFID" class="form-control" placeholder="RFID Value" ng-modal="bird.rfid"/>
<br/><br/>
<textarea id="inputComment" class="form-control" placeholder="Comment" ng-modal="bird.comment"></textarea>
<br/><br/>
<input type="file" ng-model="form.file_avatar" id="file_avatar" />
<br/><br/>
<input class="btn btn-lg btn-primary btn-block" type="submit" id="submit" value="Submit" />
</form>
</div>
</div>
My Controller Script
angular.module('test').controller('adminController', function($scope, $http)
{
$http.get('/api/adminPanel').then(function (response) {
// create a blank object to handle form data.
$scope.bird = {};
$scope.species = response.data.species;
$scope.tags = response.data.tags;
$scope.submit = function()
{
console.log(" Get fields values and Insert in the DB !");
// posting Data to server
$http.post('/api/adminPanel/create', {'bird': $scope.bird}).then(function (response) {
// sucess post
});
// failure post
}
});
});
Database script (adminPanel.js)
router.post('/create', function(req, res, next) {
var specie = req.body.specie;
var comment = req.body.comment;
var sex = req.body.sex;
// var birdSpecie = req.body.specie;
// console.log(" the Bird specie is " + birdSpecie);
console.log('the post request: ' + JSON.stringify(req.body));
database.addAnimal(specie,sex,comment).then(function()
{
res.sendStatus(200);}
,next);
});
your controller should be something like
angular.module('test').controller('adminController', function($scope, $http){
$scope.bird = {};
$scope.submit = function() {
$http.post('/api/adminPanel/create', $scope.bird).then(function (response) {
console.log(response);// as you need
});
};
});
and your server side should be:
router.post('/api/adminPanel/create', function(req, res, next) {
var specie = req.body.specie;
var comment = req.body.comment;
var sex = req.body.sex;
// your rest of code
return res.status(200).send("success") // return 200 and success message
});
I am trying to populate my json file via form. The javascript doesnt throw any error but the data doesnt load in the json file.I am new to promises as of now. I could see some posts for getting the values from the json file to view, but not vice-versa. Can anyone please help?
Service:
var module=angular.module('app',[]);
module.factory('memberDataStoreService',function($http)
{
var memberDataStore = {};
memberDataStore.addUser=function(adata){
var promise=$http({
method: 'POST',
url: 'data.json',
data: adata});
return promise;
}
return memberDataStore;
});
Controller
if ($scope.registrationForm.$valid) {
$scope.working = true;
var promise = memberDataStoreService.addUser($scope.person);
promise.success(function () {
$scope.showSuccessMessage = true;
});
promise.error(function (data, status) {
$scope.showErrorMessage = true;
});
promise.finally(function () {
$scope.working = false;
});
$scope.doShow = true;
}
html
<div ng-controller="MyController">
<form name="registrationForm" ng-submit="register()" novalidate>
<div ng-show="showSuccessMessage">
Thank you for taking the time to register!
</div>
<div class="error" ng-show="showErrorMessage">
There appears to have been a problem with your registration.<br/>
</div>
<input type="text" placeholder="First Name" name="firstName" ng-model="person.firstName" required/>
<span ng-show="firstNameInvalid"><br/>Please enter a value for First name</span>
<br/>
<input type="text" placeholder="Last Name" name="lastName" ng-model="person.lastName" required/>
<span ng-show="lastNameInvalid"><br/>Please enter a value for Last name</span>
<br/>
<input type="email" placeholder="Email" name="email" ng-model="person.email" required/>
<span ng-show="emailInvalid"><br/>A valid email address is required</span>
<br/>
<select name="research" ng-model="person.levels"
ng-options="obj.label as obj.value for obj in person.channels" required>
<option value="">Where did you hear about us?</option>
</select>
<span ng-show="researchInvalid"><br/>Please tell us where you heard about us</span>
<br/>
<input ng-model="person.newsletterOptIn" type="checkbox" name="newsletterOptIn"
id="newsletterOptIn" value="newsletterOptIn"/>
<label for="newsletterOptIn">Recieve monthly newsletter</label>
<br/>
<input ng-disabled="working" type="submit" value="Register"/>
<span ng-show="working" style="padding-left:10px;">
<img src="loading.gif"/>
</span>
</form>
</div>
</div>
As per angular promise documentation your code should look like this
https://docs.angularjs.org/api/ng/service/$q
if ($scope.registrationForm.$valid) {
$scope.working = true;
var promise = memberDataStoreService.addUser($scope.person);
promise.then(function () {
$scope.showSuccessMessage = true;
}).catch(function (data, status) {
$scope.showErrorMessage = true;
}).finally(function () {
$scope.working = false;
});
$scope.doShow = true;
}
I have been building Ionic Mobile app with AngularJS. and im trying to send email form. PHP part is working fine. i tested it with parametered URL and it worked. but with the application its not working.
here my HTML part
<form>
<div class="list list-inset">
<label class="item item-input">
<input type="text" placeholder="Name" ng-model="name">
</label>
<label class="item item-input">
<input type="text" placeholder="Email" ng-model="email">
</label>
<label class="item item-input">
<textarea row="10" cols="50" placeholder="Message" ng-model="message"></textarea>
</label>
<label class="item">
<button class="button button-block button-positive" ng-click="feedbacksubmit();">Submit</button>
</label>
</div>
</form>
and Here my ControllerJS part
$scope.feedbacksubmit= function (){
$scope.buttonclick() // to Check button has click (yes button works)
$http.post("http://boost.meximas.com/mobile/email.php?name="+name+"&email="+email+"&message="+message).success(function(data){
//$scope.tasks = data;
$scope.donemessage();
});
};
Here my PHP code
<?php
$name=$_GET['name'];
$email=$_GET['email'];
$message=$_GET['message'];
if (($name=="")||($email=="")||($message==""))
{
echo "All fields are required, please fill the form again.";
}
else{
$from="From: $name<$email>\r\nReturn-path: $email";
$subject="Message sent using your contact form";
mail("testing#gmail.com", $subject, $message, $from);
echo "Email sent!";
}
?>
Try to post the data as a JSON object and pass it as the second argument for $http.post().
var data = {
name: 'foo bar',
email: 'foo#bar.com'
};
$http.post("http://boost.meximas.com/mobile/email.php", data)
.success(function(data){
//$scope.tasks = data;
$scope.donemessage();
});
Sample Code and JsFiddle: http://jsfiddle.net/YGQT9/
app.controller('FormCtrl', function ($scope, $http) {
$scope.data = {
firstname: "default",
emailaddress: "default",
gender: "default",
member: false,
file_profile: "default",
file_avatar: "default"
};
$scope.submitForm = function() {
console.log("posting data....");
$http.post('http://posttestserver.com/post.php?dir=jsfiddle', JSON.stringify(data)).success(function(){/*success callback*/});
};
});