AngularJS form won't submit - javascript

I have this simple HTML form as below and I am using the Angular js (see the controller. - the is the form is not getting submitted and for some reason I am not able to read the values. i checked online and other questions on Stack overflow, but no success. Any pointers or guidance - what am i missing? thanks in advance :
<!doctype html>
<html ng-app="auth">
<head>
<title>Hello AngularJS</title>
</head>
<body>
<form method="post" ng-submit="login()" novalidate ng-controller="Login">
DBID<input type="text" name="dbId" value="23" ng-model="dbId" />
UserName<input type="text" name="username" value="test#test.com" ng-model="username" />
Password<input type="text" name="password" value="test1234" ng-model="password" />
<input type="submit" id="submit" value="login" />
<pre>list={{list}}</pre>
<p>The Token is: {{token}}</p>
</form>
<script src="Scripts/angular.js"></script>
<script src="Scripts/login.js"></script>
</body>
</html>
Here is my AngularJS controller:
var auth = angular.module('auth', []);
auth.controller('Login', function ($scope, $http)
{
$scope.login = function ()
{
if ($scope.dbId)
{
$scope.list.push(this.dbId);
$scope.text = '';
}
};
var Credentials = new Object();
Credentials.DBID = "23";
Credentials.username = "test#test.com";
Credentials.password = "test1234";
$http({
dataType: 'json',
method: 'POST',
url: 'http://localhost:55049/api/Security/Login',
data: Credentials,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic VGVzdEFwcGxpY2F0aW9uVG9rZW46'
}
}).then(function (response)
{
$scope.token = response.data;
});
});
Thanks

i think you are closing the login function brace too early. adjusted it and try again.
var auth = angular.module('auth', []);
auth.controller('Login', function ($scope, $http)
{
$scope.login = function ()
{
if ($scope.dbId)
{
$scope.list.push(this.dbId);
$scope.text = '';
}
var Credentials = new Object();
Credentials.DBID = "23";
Credentials.username = "test#test.com";
Credentials.password = "test1234";
$http({
dataType: 'json',
method: 'POST',
url: 'http://localhost:55049/api/Security/Login',
data: Credentials,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic VGVzdEFwcGxpY2F0aW9uVG9rZW46'
}
}).then(function (response)
{
$scope.token = response.data;
});
};
});

I added some modifications to the JavaScript code and it's working fine.
Please take a look and run the sample code to see it in action. Also I changed the username, DBID and password to be dynamic with input values.
var auth = angular.module('auth', []);
auth.controller('Login', function($scope, $http) {
$scope.list = [];
$scope.login = function() {
if ($scope.dbId) {
$scope.list.push(this.dbId);
$scope.text = '';
var Credentials = new Object();
Credentials.DBID = $scope.dbId;
Credentials.username = $scope.username;
Credentials.password = $scope.password;
alert("Posting your data: " + JSON.stringify(Credentials));
$http({
dataType: 'json',
method: 'POST',
url: 'http://localhost:55049/api/Security/Login',
data: Credentials,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic VGVzdEFwcGxpY2F0aW9uVG9rZW46'
}
}).then(function(response) {
$scope.token = response.data;
});
} else {
alert("Please add DBID");
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="auth" ng-controller="Login">
<form method="post" ng-submit="login()" novalidate ng-controller="Login">
DBID<input type="text" name="dbId" value="23" ng-model="dbId" /> UserName
<input type="text" name="username" value="test#test.com" ng-model="username" /> Password
<input type="text" name="password" value="test1234" ng-model="password" />
<input type="submit" id="submit" value="login" />
<pre>list={{list}}</pre>
<p>The Token is: {{token}}</p>
</form>
</div>

Related

How to create service and use it in controller

I am having a simple login form and I want to validate user upon successful HTTP request and it works fine. however, I've written all the code in the controller itself and I don't want that. i am new to angularjs so i have trouble creating service. so I need to create service for my logic. can anyone create service for the logic in the controller so that code works exactly same?
sample.html(for now it only prints username, password, and status code of response)
<html>
<head>
<script src="angular.js"></script>
<script src="angular.min.js"></script>
<script src="angular-route.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="myapp">
<div ng-controller="mycontroller">
Username <input type="text" ng-model="login" /><br><br> Password <input
type="password" ng-model="pass" /><br>
<button type="submit" ng-click="myfunc()">Login</button>
<center>User name is {{ login }}, password is{{pass}}<br>
{{success.code}}
</div>
</body>
</div>
</body>
</html>
Controller
var app = angular.module("myapp", []);
app.controller("mycontroller", function($scope, $http, $log) {
$scope.login = "";
$scope.pass = "";
$scope.myfunc = function() {
var obj = {
login_id: $scope.login,
password: $scope.pass
}
var mydata = JSON.stringify(obj);
$http({
method: 'POST',
url: "http://myapiurl.com/signin/",
headers: {
"authorization": "oauth mytoken",
'Access-Control-Allow-Origin': '*'
},
data: mydata
}).then(function(response) {
console.log(response)
$scope.success = response.data;
},
function(reason) {
$scope.error = reason.data
console.log(reason);
$log.info(reason.data);
});
}
});
Super simple. First create a service, which injects $http module. Make a method you can call which returns promise from the $http module. In this example it's a get method.
app.service("ExampleService", function($http){
this.ExampleRequest = function(){
return $http.get('url');
}
});
Inject the service created above and you can call the functions you've defined in the service. Notice that the .then comes from the promise.
app.controller("exampleCtrl", function($scope, ExampleService){
$scope.onClick = function(){
ExampleService.ExampleRequest().then(function(data){
// Do something with data
});
}
});
Create a myService factory and create a function to send http req and return the response.
app.factory('myService', function($http) {
return {
httpReq: function(data) {
return $http({
method: 'POST',
url: "http://myapiurl.com/signin/",
headers: {
"authorization": "oauth mytoken",
'Access-Control-Allow-Origin': '*'
},
data: data
})
}
}
});
Now call it from the controller.
app.controller("mycontroller", function($scope, myService, $log) {
$scope.login = "";
$scope.pass = "";
$scope.myfunc = function() {
var obj = {
login_id: $scope.login,
password: $scope.pass
}
var mydata = JSON.stringify(obj);
myService.httpReq(mydata)
.then(function(response) {
console.log(response)
$scope.success = response.data;
},
function(reason) {
$scope.error = reason.data
console.log(reason);
$log.info(reason.data);
});
}
});

ng-model is not working with ng-value in AngularJS

Below is my View page
<form name="form">
<label>Name</label>
<input name="name" type="text" ng-model='user.name' ng-value='emp.name' required />
<span ng-show="form.name.$touched && form.name.$invalid">Name is required</span>
<button ng-disabled="form.name.$touched && form.name.$invalid" ng-click='formUpdate()'>Update</button>
</form>
This is my controller
$scope.formUpdate = function() {
$scope.status = false;
$http({
method : 'POST',
url : 'model/update.php',
data : $scope.user ,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function mySuccess(response) {
$scope.update = response.data;
console.log(response.data);
}, function myError(response) {
$scope.update = response.statusText;
});
};
When I am using data: $scope.user in my HTTP call I am getting blank values on console but if I used data: $scope.emp, then I never get updated values of input fields rather getting old values of input fields.
ng-value binds the given expression to the value of the element.
As I understand your question, you are trying to initialize the input value to emp.name.
You should change your input to:
<input type="text" ng-model='user.name' ng-init='user.name = emp.name' required />
ng-init docs
try this code;
$scope.formUpdate = function(){
$scope.status = false;
$scope.$applyAsync();
$http({
method : 'POST',
url : 'model/update.php',
data : $scope.user ,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function mySuccess(response) {
$scope.update = response.data;
$scope.$applyAsync();
console.log(response.data);
}, function myError(response) {
$scope.update = response.statusText;
$scope.$applyAsync();
});
};

ng-model as initial input on form

I have an edit form that pushes data to a mongo db using express and angular. I am using ng-model for my data. The PUT works correctly to update the database. But I can't seem to make that found data as initial values on the input fields in my GET. I think I am binding things incorrectly. If that is the case, what am I doing wrong?
Thanks in advance.
My controller
app.controller('EditController', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {
var self = this;
$http({
method: 'GET',
url: '/users/' + $routeParams.id,
data: $routeParams.id
}).then(function(response) {
// console.log(response.data);
self.id = $routeParams.id;
self.name = response.data.name;
self.age = response.data.age;
self.gender = response.data.gender;
self.img = response.data.img;
});
this.editForm = function() {
console.log('editForm');
console.log('Formdata: ', this.formdata);
$http({
method: 'PUT',
url: '/users/' + $routeParams.id,
data: this.formdata,
}).then(function(result) {
self.formdata = {}
});
} // end editForm
}]);
// end EditController
app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider){
$locationProvider.html5Mode({enabled:true});
$routeProvider.when('/', {
templateUrl: 'partials/match_partial.html'
}).when('/edit/:id', {
templateUrl: 'partials/edit_partial.html',
controller: 'EditController',
controllerAs: 'editctrl'
})
}]);
My HTML
<div>
<a ng-href="/">
<br>
<h3 class="back">Back to Match</h3>
</a>
<h1 class="editHeader">
Edit {{editctrl.name}}
</h1>
<form ng-submit="editctrl.editForm()">
<input type="text" ng-model="editctrl.formdata.id" placeholder="{{editctrl.id}}">
<input type="text" ng-model="editctrl.formdata.name" placeholder="{{editctrl.name}}">
<input type="text" ng-model="editctrl.formdata.age" placeholder="{{editctrl.age}}">
<input type="text" ng-model="editctrl.formdata.gender" placeholder="{{editctrl.gender}}">
<input type="text" ng-model="editctrl.formdata.img" placeholder="{{editctrl.img}}">
<input type="submit">
</form>
</div>
You can simply set the whole object to receive the response.data, this way:
$http({
method: 'GET',
url: '/users/' + $routeParams.id,
data: $routeParams.id
}).then(function(response) {
// console.log(response.data);
// Here
self.formdata = response.data;
});
And it will automatically fills all inputs with the object properties.

angular js: Error: $ is not defined in http post

I'm trying to post values from a form. Form has two fields- name and email. I have setup the controller as well but when i try to post, error is shown.
<form name="save" ng-submit="sap.saved(save.$valid)" novalidate>
<div class="form-group" >
<input type="text" name="name" id="name" ng-model="sap.name" />
</div>
<div class="form-group" >
<input type="email" name="email" id="email" ng-model="sap.email" />
</div>
<div class="form-actions">
<button type="submit" ng-disabled="save.$invalid || sap.dataLoading">Save</button>
</div>
</form>
My controller is:
(function() {
angular
.module('myApp.saved', [])
.controller('dataController', function($scope, $http) {
var sap = this;
$scope.post = {};
$scope.post.login = [];
$scope.sap = {};
$scope.index = '';
var url = 'save.php';
sap.saved = function(isValid)
{
if (isValid)
{
$http({
method: 'post',
url: url,
data: $.param({'user' : $scope.sap }),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function(response)
{
// success
alert('success');
},
function(response)
{
// failed
alert('failed');
});
}
};
});
})();
When i submit, $ is not defined is shown. I'm pretty much new in angular. Can anyone tell what all mistakes I made?
$ is alias for jQuery and param is a jquery method.
Have you included jQuery?
data: $.param({'user' : $scope.sap }),
should be
data: {
'user': $scope.sap //POST parameters
}
data – {string|Object} – The response body transformed with the transform functions

Controller error in Angular Script - [$injector:modulerr]

I'm not sure about the controller syntax. I keep getting an [$injector:modulerr] error which leads me to believe that it's the controller playing up but I'm lost otherwise. My main objective at the moment is that I'm trying to "get" and display all the results from a couchdb database.
<div ng-app="guestBook">
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js">
</script>
<script>
var guestBook = angular.module('guestBook', ['ngRoute'])
guestBook.controller('CouchController', ['$scope', '$http', '$get', function ($scope, $http, $get) {
// View everything in database
$scope.view = function () {
var json = {};
var url = "https://sophia.iriscouch.com/guestbook/_all_docs";
$get({
url: url,
method: 'GET',
data: json,
dataType: "jsonp",
}).success(function (json, status, headers, config) {
console.log(json);
})
};
// Creating a new instance on couchDB
$scope.submit = function () {
var entry = {
"Name": $scope.name,
"Comment": $scope.comment
};
console.log(entry);
var timestamp = Math.round(new Date().getTime() / 1000);
var url = 'https://sophia.iriscouch.com/guestbook/' + timestamp;
console.log(url);
$http({
url: url,
method: 'PUT',
data: entry,
dataType: "json",
withCredentials: true,
headers: {
'Authorization': auth_hash("sophia", "Einstein1")
}
}).success(function (data, status, headers, config) {
console.log(data);
}).error(function (data, status, headers, config) {
console.log(headers);
console.log(config);
});
}
function auth_hash(username, password) {
var str = window.btoa(username + ":" + password);
return 'Basic' + str;
}
}]);
</script>
<form ng-controller="CouchController">
<p>
<input type="text" ng-model="comment">
</p>
<p>
<input type="text" ng-model="name">
</p>
<p>
<button ng-click="submit()">Add</button>
</p>
<p>
<button ng-click="view()">show</button>
</p>
</form>
you specify the dependent ngRoute module like
angular.module('guestBook', ['ngRoute'])
but you didn't add angular-route.js script file. adding that file will solve this.
here is the CDN of ngRoute module
after adding it the code should be like,
<div ng-app="guestBook">
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.6/angular-route.js"></script>
....

Categories

Resources