Angular Form Post - angularjs

I have the following code and when I submit the request; I get request failed. The data is not going to the server. Any idea why?
All I need is a simple form submission with the code below. I think the issue is where I'm collecting the form data using the config section. I looked around and that's how I added that. Any help will be appreciated.
Thanks.
<!-- Main Content -->
<div class="container">
<div class="page-header" ng-controller="NotesCtrl">
<h1>{{title}}</h1>
<form class="row-height" name="Form1" ng-submit="processForm('ajaxSubmitResult')">
<!--ng-submit="processForm(formData, 'ajaxSubmitResult') -->
First Name:
<input type="text" ng-model="formData.firstname" class="spacer" required/>
Last Name:
<input type="text" ng-model="formData.lastname" class="spacer" required/>
<!--<button class="btn btn-primary" ng-click="insert(formData)">Add</button>-->
<button type="submit" class="btn btn-success">Add Name</button>
</form>
<hr/>
<h4>Raw Data</h4>
{{formData}}
<hr/>
<h4>Submit Results</h4>
<span id="submitDebugText">{{ajaxSubmitResult | json}}</span>
</div>
</div>
<script>
// define angular module/app
var formApp = angular.module('formApp', []);
function NotesCtrl($scope, $http) {
$scope.title = "Test App";
$scope.formData = {};
$scope.processForm = function (resultVarName) {
var config = {
params: {
'firstname': $scope.firstname,
'lastname': $scope.lastname
}
};
$http.post("//", null, config)
.success(function (data, status, headers, config) {
$scope[resultVarName] = data;
})
.error(function (data, status, headers, config) {
$scope[resultVarName] = "bugger! Errors.";
});
};
}
</script>

When you do something like this in the view:
<input type="text" ng-model="formData.firstname" class="spacer" required/>
In the controller, you access the property with
$scope.formData.firstName
This issue seems to be that you aren't including the formData here:
var config = {
params: {
'firstname': $scope.firstname,
'lastname': $scope.lastname
}
};
Change that to
var config = {
params: {
'firstname': $scope.formData.firstname,
'lastname': $scope.formData.lastname
}
};
And you should be good to go.

Related

How to pass data-plugin="timepicker" value to controller in angularJS

I have code to pass date and time to controller.
Here is HTML code,
<div class="page-content" ng-app="app">
<div ng-controller="postAppoinmentCtr as ctrl" class="panel-body">
<form ng-submit="submitForm()" id="form1">
<input name="time" ng-model="time" type="text" class="form-control" ng-model="time" data-plugin="timepicker" autocomplete="off"/>
<input name="date" ng-model="date" type="text" class="form-control" data-plugin="datepicker"/>
<input..ng-model="type"...></input>
<input..ng-model="Description"...></input>
<button ...>
</form>
</div>
</div>
Here is angular js part
var app = angular.module('app', []);
app.controller('postAppoinmentCtr', function($scope, $http, $location) {
$scope.submitForm = function(){
var url = $location.absUrl() + "/addAppoinment";
alert(url);
var config = {
headers : {
'Content-Type': 'application/json;charset=utf-8;'
}
}
var data = {
type: $scope.type,
date: $scope.date,
time: $scope.time,
description: $scope.description
};
$http.post(url, data, config).then(function (response) {
$scope.postResultMessage = "Sucessful!";
}, function (response) {
$scope.postResultMessage = "Fail!";
});
$scope.type = "";
$scope.date = "";
$scope.time ="";
$scope.description ="";
}
});
When click the button type and description pass to controller. But date and time not. I can do this using
<input id="date-birth" class="form-control" type="date" ng-model="date">
this line. But I need to use data-plugin="datepicker" .
I'm new one for the angularjs and I try to many ways for solve this problem.
Please give me some answer this. Thanks in advance.

Angular contact form - undefined field after after sending

Here is my index.html
<div data-ng-controller="help">
<div id="messages" class="alert alert-success" data-ng-show="messages" data-ng-bind="messages"></div>
<div data-ng-show="progress.active()" style="color: red; font-size: 50px;">Sending…</div>
<form name="helpForm" novalidate role="form">
<div class="form-group">
<label for="name">Your Name </label>
<span class="label label-danger" data-ng-show="submitted && helpForm.name.$error.required">Required!</span>
<input type="text" name="name" data-ng-model="userName" class="form-control" required />
</div>
<div class="form-group">
<label for="email">Your E-mail address</label>
<span class="label label-danger" data-ng-show="submitted && helpForm.email.$error.required">Required!</span>
<span class="label label-danger" data-ng-show="submitted && helpForm.$error.email">Invalid email!</span>
<input type="email" name="email" data-ng-model="userEmail" class="form-control" required />
</div>
<div class="form-group">
<label for="message">Message</label>
<span class="label label-danger" data-ng-show="submitted && helpForm.message.$error.required">Required!</span>
<textarea name="message" data-ng-model="userMessage" class="form-control" required></textarea>
</div>
<button data-ng-disabled="progress.active()" data-ng-click="submit(helpForm)" class="btn btn-default">Submit</button>
</form>
And part of my app.js
angular.module('myApp', ['ajoslin.promise-tracker'])
.controller('help', function ($scope, $http, $log, promiseTracker, $timeout) {
$scope.subjectListOptions = {
'bug': 'Report a Bug',
'account': 'Account Problems',
'mobile': 'Mobile',
'user': 'Report a Malicious User',
'other': 'Other'
};
$scope.progress = promiseTracker();
$scope.submit = function(form) {
$scope.submitted = true;
if (form.$invalid) {
return;
}
var $promise = $http({
method: 'POST',
url:'api/contactUs',
params: {
'callback' : 'JSON_CALLBACK',
'userName' : $scope.userName,
'userEmail' : $scope.userEmail,
'userMessage' : $scope.userMessage
}
})
.success(function(data, status, headers) {
if (data.status == 'OK') {
$scope.userName = null;
$scope.userEmail = null;
$scope.userMessage = null;
$scope.messages = 'Your form has been sent!';
$scope.submitted = false;
} else {
$scope.messages = 'Oops, we received your request, but there was an error processing it.';
$log.error(data);
}
})
.error(function(data, status, headers) {
$scope.progress = data;
$scope.messages = 'There was a network error. Try again later.';
$log.error(data);
})
.finally(function() {
$timeout(function() {
$scope.messages = null;
}, 9000);
});
After sending the letter to mail, all fields (name, email, message) in the form are displayed as "Undefined"
I use an node.js server and connect via api (api/contactUs)
I can not understand what the problem is, already tried everything I could, but the error remains.
Please help with the solution of this problem.
Thank you in advance!
When you use POST method, you should pass data object instead of params object.
Change this:
params: {
'callback' : 'JSON_CALLBACK',
'userName' : $scope.userName,
'userEmail' : $scope.userEmail,
'userMessage' : $scope.userMessage
}
To this:
data: {
'callback' : 'JSON_CALLBACK',
'userName' : $scope.userName,
'userEmail' : $scope.userEmail,
'userMessage' : $scope.userMessage
}

ng-model data not getting when saving the data

here save the ng-model is newattendance saving to database. "newattendance._id" is not taken as a ng-model.how to make it "newattendance._id" is ng-model
<select class="form-control" ng-options="item.empcode as item.empcode for item in totemplist" ng-model="item.empcode">
</select>
<input type="text" ng-repeat="newattendance in totemplist" ng-model="newattendance._id" ng-show="item.empcode ==newattendance.empcode" style="width:200px;" ><br>
<input placeholder="Enter Attendacne Date" ng-model="newattendance.doa">
<button class="btn btn-primary" ng-click="checkOut()">checkOut</button>
Controller
EmpMasterController.controller("AttendanceController", ['$scope', 'AttendanceFactory',"EmpAddService", function($scope, AttendanceFactory,EmpAddService){
$scope.newattendance={};
$scope.totemplist=EmpAddService.getAllEmpAddItems();
console.log($scope.totemplist);
$scope.checkIn = function(){
AttendanceFactory.addAttendance($scope.newattendance);
$scope.newattendance = {}
}
$scope.getAllAttendance = function(){
console.log("$$$$$"+$scope.newattendance._id)
$scope.attendancedetails =AttendanceFactory.getAllAttendance($scope.newattendance._id);
}
}])
Factory
EmpFactModule.factory("AttendanceFactory", function($resource, RES_URL){
var attendanceResource = $resource(RES_URL+"attandence/:id/:attid",
{"id": "#id", "attid": "#attid"}, {update: {method: "PUT"}})
var attendanceDetails;
return {
addAttendance: function(newattendance){
console.log("..1.. " + newattendance._id)
attendanceResource.save({"id":newattendance._id}, newattendance, function(data){
console.log("Add Success ")
}, function(data, status){
console.log("Add Failed*****");
})
},
getAllAttendance: function(_id){
console.log("..#.. " + _id)
attendanceDetails = attendanceResource.query({"id": _id});
return attendanceDetails;
},
}
})
please help me how make it as ng-model and how to save this...
I've create a JSFiddle for you which hopefully will help you understand the 2 way binding in angular.
you dont need to pass the newattendance object to the check-out function, it is already saved on the scope.
HTML:
<div ng-app="app">
<div ng-controller="formValidation">
<div>
<div>
<span>User Name</span>
<input type="text" placeholder="John" ng-model="newattendance._id">
<span>
<button ng-click="submit()">
check out
</button>
</span>
</div>
</div>
<pre>{{newattendance._id}}</pre>
</div>
</div>
JS:
var app = angular.module('app', []);
app.controller('formValidation', function($scope) {
$scope.submit=function(){
var formPost = {
"Username":$scope.newattendance._id
};
console.log(formPost);
}
});

Angularjs list not refreshing on form submit using MEAN

Some what new to the MEAN stack. Currently I'm reworking an small app I did through codeschool to be full MEAN stack.
The app created can be seen here
Code School app
In rewriting the app using the MEAN stack after submitting the form I must refresh the page to see the city added to the list. What do I need to fix so I don't need to refresh the page for the new Item to be added to the list?
If I'm missing any relevant code below here is my git hub link
git hub link
Here is my code:
angular.module('Cityapp').controller('CityIndexController', function(City, $scope){
$scope.cities = City.query();
window.sc = $scope;
});
angular.module('Cityapp').controller('CityCreateController', function(City, $scope, $http){
$scope.city = new City();
$scope.saveCity = function(city){
$http({
method: 'POST',
url: '/city',
data: city})
.success( function(data, status, headers, config){
console.log($scope.city);
console.log(data);
console.log($scope.city);
}).
error(function(data,status,headers,config){
jQuery('.alert').show();
console.log('nope');
});
};
});
<form ng-controller="CityCreateController">
<legend> New City</legend>
<input for="City-group" name="City" id="City" type="text" ng-model="city.city" placeholder="City Name">
<input for="City-group" name="desc" id="desc" type="text" ng-model="city.desc" placeholder="Description">
<input type="submit" class="btn btn-default" ng-click="saveCity(city)"/>
</form>
<ul ng-controller="CityIndexController" class="city-list">
<li ng-repeat="city in cities">
<a href="#">
{{city.city}}</a></li>
</ul>
It should looks something like that
;(function() {
function Cities($http) {
function City() {
}
City.prototype.save = function() {
return $http.post('/api/city', this);
};
City.cities = [];
City.add = function(city) {
city.save().then(function() {
City.cities.push(city);
});
};
City.getAll = function() {
$http.get('/api/cities').then(function(response) {
City.cities = response.data.map(function(data) {
return new City(data);
});
return cities;
});
};
return City;
}
function CityCreateController(Cities) {
var mv = this;
mv.city = new Cities();
mv.saveCity = function() {
Cities.add(mv.city);
};
}
function CityIndexController($scope, Cities) {
var mv = this;
$scope.$watchCollection(function() {
return Cities.cities;
}, function(cities) {
mv.cities = cities || [];
});
Cities.getAll();
}
angular
.module('app', [])
.factory('Cities', ['$http', Cities])
.controller('CityCreateController', ['Cities', CityCreateController])
.controller('CityIndexController', ['$scope', 'Cities', CityIndexController]);
})();
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<meta charset="utf-8">
</head>
<body ng-app="app">
<form ng-controller="CityCreateController as mv">
<legend> New City</legend>
<input for="City-group" name="City" id="City" type="text" ng-model="mv.city.city" placeholder="City Name">
<input for="City-group" name="desc" id="desc" type="text" ng-model="mv.city.desc" placeholder="Description">
<input type="submit" class="btn btn-default" ng-click="mv.saveCity()"/>
</form>
<ul ng-controller="CityIndexController as mv" class="city-list">
<li ng-repeat="city in mv.cities">
<a href="#">
{{city.city}}</a></li>
</ul>
</body>
</html>
Found a simple fix
angular.module('Cityapp').controller('CityCreateController', function(City, $scope, $http){
$scope.cities = City.query();
$scope.city = new City();
$scope.saveCity = function(city){
$http({
method: 'POST',
url: '/city',
data: city})
.success( function(data, status, headers, config){
$scope.cities.push({city: $scope.city.city,
desc: $scope.city.desc});
}).
error(function(data,status,headers,config){
jQuery('.alert').show();
console.log('nope');
});
};
});
Just added the
$scope.cities.push({city: $scope.city.city,
desc: $scope.city.desc});
to the .success. Works like it should. Now on to my next issue.

Submit form with ng-submit and trigger synchronous post request

I have a form that I want to trigger validation on when the user clicks submit. If the validation fails, then suitable error messages are displayed. This much works.
However if the validation passes I want the form to submit a synchronous POST request with full page reload as if the action and method parameters were set as usual.
How does one achieve trigger the normal post action (not AJAX) from the ng-submit function on the AngularJS scope?
My form of course looks basically like the following:
<form id="myForm" name="myForm" ng-submit="formAction(this, models)">
...
<input type="submit" value="Submit">
</form>
The best I can think of is to mirror the contents of the form with another hidden form submitting that one, but there must be a better way!
TO CLARIFY: If validation passes, I need the form submission to essentially behave like a normal synchronous post form submission which lands the user at the page returned by the server from the post request.
http://plnkr.co/edit/cgWaiQH8pjAT2IRObNJy?p=preview
Please check this plunkr
Basically what I am doing is passing the $event object. form is the target of the event object, and we can submit it.
function Ctrl($scope) {
$scope.list = [];
$scope.text = 'hello';
$scope.submit = function($event) {
if ($scope.text) {
$scope.list.push(this.text);
if(this.text === 'valid'){
$event.target.submit();
}
$scope.text = '';
}
};
}
Try inside formAction after you've submitted the data:
$route.reload();
I dont think you need to do a full page refresh. You have a single page app I am assuming; use it. Try something like this:
<section class="contact">
<article>
<h1>Contact</h1>
<form role="form" name="contactForm" ng-submit="formSubmit(contactForm)">
<div class="form-group">
<input class="form-control" ng-model="name" name="name" id="name" type="text" placeholder="Name" required/>
</div>
<div class="form-group">
<input class="form-control" ng-model="email" name="email" id="email" type="email" placeholder="Email Address" required/>
</div>
<div class="form-group">
<textarea class="form-control" ng-model="message" name="message" id="message" rows="5"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-lg">Send Message</button>
<a class="btn btn-default btn-lg" href='mailto:me#something.net'>Or email me</a>
</div>
</form>
</article>
'use strict';
MyApp.controller('ContactController', function ContactController ($scope, EmailService) {
$scope.formSubmit = function(form) {
EmailService.send(form).then(function(data) {
if(data.message.sent) {
$scope.resetForm();
alert("Message Sent");
}
else {
alert("Something went wrong. Try emailing me.");
}
});
}
$scope.resetForm = function() {
$scope.name = "";
$scope.email = "";
$scope.message = "";
}
});
MyApp.factory('AjaxService', function AjaxService ($q, $http) {
return {
http: function(ajaxParams) {
var deferred = $q.defer();
$http(ajaxParams)
.success(function (data, status, headers, config) {
deferred.resolve({
success: true,
status: status,
message: data
});
})
.error(function (data, status, headers, config) {
deferred.reject({
success: false,
status: status,
message: "Http Error"
});
});
return deferred.promise;
}
}
});
MyApp.factory('EmailService', function EmailService (AjaxService) {
return {
send: function(emailData) {
var ajaxParams = {
method: 'POST',
url: ''//where ever your form handler is,
data: {
name: emailData.name.$modelValue,
email: emailData.email.$modelValue,
message: emailData.message.$modelValue
},
cache: false
}
return AjaxService.http(ajaxParams);
}
}
});

Resources