How to submit a straightforward form using Angular - javascript

Using angular, I want to submit a form and store the response. My code looks something like this:
<form ng-controller="myController" action="myAction" method="POST">
<input type="text" name="name" />
<input type="submit" ng-click="submit" />
</form>
<script>
function myController($scope, $http) {
$scope.submit = function() {
$http.post(url, data).success(function(data) {
$scope.result = data;
});
}
}
</script>
How do I get url and data to be the form action and inputs, respectively? I don't want to send JSON, I want the server side to see this is a regular HTML form submit.

Thank, #Vincent Ramdhanie, for pointing me in the right direction. Here's what I ultimately did, using plenty of jQuery thrown in:
function myController($scope, $http) {
$('form').submit(function() {
return false;
});
$scope.submit = function() {
form = $('form');
data = form.serialize();
url = form.attr('action')
$http.post(url, data,
{ headers:
{ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
}).success(function(data) {
$scope.result = data;
}
);
}
}

This is how I accomplish this, start by binding the form data to your model, Then use a transform to transform your JSON data into regular post parameters. This solution depends on the jQuery param() function:
<form ng-controller="myController" method="POST">
<input type="text" name="name" ng-model="name"/>
<input type="submit" ng-click="submit" />
</form>
function myController($scope, $http) {
$scope.name = "";
/* Helper function to transform the form post to a regular post rather than JSON */
var transform = function(data) {
return $.param(data);
}
$scope.submit = function() {
$http.post('myAction', $scope.name, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
transformRequest: transform
})
.success(function (data) {
$scope.result = data;
});
}
}

Related

Refresh/ Re Render the UI once Submit button is clicked

Currently I am using AnularJS to update the value from JSON file and Once I click Submit button , I want to clear the whole DOM and refresh the UI and update the contents. Can you please help here
Here Value1 and Value2 comes from two different functions but sometimes . Value2 will be null and only Value1 will be present. but still Value2 will be shown with Old value and Value1 with updated value after clicking submit button.
Is there any way in AngularJS to refresh the DOM before updating the values. so that once i click submit i should be seeing only Value1
var app = angular.module('myApp', ['angular-loading-bar']);
app.controller("Controller", ["$scope", "$http", "$window",
function ($scope, $http, $window) {
$scope.firstFunction = function () {
$http({
method: 'POST',
url: 'one.php',
//headers : {'Content-Type':'application/x-www-form-urlencoded'},
data: {
"accountnumber": $scope.accountnumber,
"environment": $scope.selectedVal,
},
}).then(function (response) {
var data = response.data;
$scope.post = response.data;
$scope.value1 = response.data
//$scope.secondFunction(data);
}, function (error) {
var data = error.data;
console.log("Error" + data);
})
}
$scope.secondFunction = function () {
$http({
method: 'POST',
url: 'two.php',
//headers : {'Content-Type':'application/x-www-form-urlencoded'},
data: {
"accountnumber": $scope.accountnumber,
"environment": $scope.selectedVal,
},
}).then(function (response) {
var data = response.data;
$scope.post = response.data;
$scope.value2 = response.data
console.log($scope.cellularIPAddressValue);
//$scope.secondFunction(data);
}, function (error) {
var data = error.data;
console.log("Error" + data);
})
}
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html>
<body ng-app="myApp">
<div ng-controller="Controller">
<div class="row">
<div class="input-group form-search">
<input type="text" ng-model="accountnumber" name="accountnumber" class="form-control search-query" placeholder="Enter Account Number">
<span class="input-group-btn">
<button type="submit" ng-click="firstFunction();secondFunction();" class="btn btn-primary">Submit</button>
</span>
<span id="message">{{value1}}</span>
<span id="message">{{value2}}</span>
</div>
</div>
</div>
</body>
</html>
There is no need to refresh UI as angular data-binding does the job.
Changing the ng-click="firstFunction();secondFunction();"
to ng-click="value1=null;value2=null;firstFunction();secondFunction();" may help.

Input field should not clear after submit using angularjs

HTML
<form ng-controller="updatecontroller" ng-submit="updateUser()"><label class="control-label">First Name</label>
<input type="text" ng-model="user.userFirstName">
<label class="control-label">Last Name</label>
<input type="text" ng-model="user.userLastName" ><button type="submit" ng-click="updateUser()">Update</button>
</form>
JS
app.controller('updatecontroller', function ($scope, $http, $cookieStore) {
$http.get('http://localhost:8080/myapp/user/'.concat($scope.getUserId) + '?access_token=' + $cookieStore.get("access_token")).
then(function (response) {
$scope.user = response.data;
});$scope.user = {"id": "","userFirstName": "","userLastName": ""}
$scope.updateUser = function () {
var url = "http://localhost:8080/myapp/user/".concat($scope.getUserId) + "?access_token=" + $cookieStore.get("access_token");
var method = "PUT";
$http({
method: method,
url: url,
data: angular.toJson($scope.user),
headers: {
'Content-Type': 'application/json'
}
})
};});
values will appear in text field. i have to update. the values are getting updated in database. but what i want is.. the updated values should not clear after submit the form.
Thanks!
You can empty the input filed after get the response from HTTP request
$scope.updateUser = function () {
$http({
method: 'POST',
url: 'myUri',
data: 'your data'
headers:'header'
}).then(
function(res) {
$scope.user = {"id": "","userFirstName": "","userLastName": ""} //clear the input field here
},
function(err) {
}
);
}
Place your Submit Button inside the Form Element then try it it will clear the input after the submission.
your updateUser() method seems to be the problem. It's probably clearing user.userFirstName & user.userLastName (or the whole user)
please show us what updateUser() is doing to be sure

Posting data to MVC Controller using AngularJS

I have a simple html form with 2 textboxes and a button as following:
<div class="container" ng-controller="GetStudentController">
<div class="form-group" style="padding-bottom:40px;">
<h2 style="text-align:center;">Index</h2>
<input id="Text1" class="form-group form-control" ng-model="ime" type="text" />
<input id="Text1" class="form-group form-control" ng-model="prezime" type="text" />
<input type="button" style="float:right;" class="form-group btn btn-primary" ng-click="snimi(ime,prezime)" value="Snimi" />
</div>
</div>
And this is my AngularJS code:
var app = angular.module("myApp", []);
app.service("GetStudentsService", function ($http) {
this.getData = function ()
{
return $http({
metod: "GET",
url: "/Home/GetStudent"
}).success(function (data) {
return data;
}).error(function () {
alert("error");
return null;
});
}
this.PostData = function (data)
{
$http.post("/Home/SnimiStudenta",data)
.success(function () {
getData();
}).error(function (response) {
alert(response);
});
}
});
app.controller("GetStudentController", function ($scope, GetStudentsService) {
$scope.data = null;
GetStudentsService.getData().then(function (response) {
$scope.data = response.data;
});
$scope.snimi = function (ime, prezime) {
var data = $.param({
fName: ime,
lName: prezime
});
GetStudentsService.PostData(data);
};
});
And this is the action responsible for saving the record to the DB:
[HttpPost]
public void SnimiStudenta(// I would like to pass an Student object here)
{
Student s = new Student();
s.Ime = "1";
s.Prezime = "2";
Connection.dc.Students.Add(s);
Connection.dc.SaveChanges();
}
I have a few questions:
How can I mark my values from my textboxes and pass them as an Student object into my action
How can I bind the table upon saving the new record into the DB. As you can see I'm calling the function getData(); but it says its undefined...
Can someone help me out with this please?
Thanks!
You have to build a js object which looks similar to your C# class (In terms of the property name) which you use as the parameter for your action method, and post the js object
$scope.snimi = function (ime, prezime) {
var data = { Ime: ime, Prezime: prezime};
GetStudentsService.PostData(data);
};
And your action method,
[HttpPost]
public void SnimiStudenta(Student s)
{
Connection.dc.Students.Add(s);
Connection.dc.SaveChanges();
}
As far as why you get an "undefined" error when you call getData(), it is not because getData is undefined, but because getData returns a promise containing just the data, not the whole response. So change:
GetStudentsService.getData().then(function (response) {
$scope.data = response.data;
});
to:
GetStudentsService.getData().then(function (data) {
$scope.data = data;
});

AngularJS: Call httpget on value change from textbox

I have a web service which returns json file on call with a parameter for the id of an entry. I have a angular method that returns the data returned from that method. I have no idea how to recall the service when the input of the id has changed as I want to recall that method when a new value has been supplied.
The parameter that I pass in for the Id is called Reference. The HTML returns object with a reference of 1234 but if I change the value I dont know how to recall the service.
This is what I have so far:
Angular:
var app = angular.module("myModule", [])
.controller("myController", function ($scope, $http) {
var res = $http({
method: 'GET',
url: 'AirPortrWebService.asmx/DashboardDetail',
params: { Reference : '1234' }
})
.then(function (response) {
$scope.booking = response.data
});
$scope.test = "Angular Method Called";
$scope.Reference = '1234';
});
Html
<!DOCTYPE html>
<html>
<head>
<script src="scripts/angular.js"></script>
<script src="app/NewAppTwo.js"></script>
</head>
<body ng-app="myModule" ng-controller="myController">
{{test}}
{{Reference}}
<br />
<br />
<input type="text" ng-model="Reference" ng-change="booking"/>
{{booking}}
</body>
</html>
Change ng-change="booking" to a function that is called everytime that models Refences changes:
$scope.getReference = function(referenceNumber){
$http({
method: 'GET',
url: 'AirPortrWebService.asmx/DashboardDetail',
params: { Reference : referenceNumber}
}).function (response) {
$scope.booking = response.data
});
}
<input type="text" ng-model="Reference" ng-change="getReference(Reference)"/>
try this :
var app = angular.module("myModule", [])
.controller("myController", function ($scope, $http) {
$scope.refresh = function(){
var res = $http({
method: 'GET',
url: 'AirPortrWebService.asmx/DashboardDetail',
params: { Reference : $scope.Reference }
})
.then(function (response) {
$scope.booking = response.data
});
}
$scope.test = "Angular Method Called";
$scope.Reference = '1234';
});
and html
<input type="text" ng-model="Reference" ng-change="refresh()"/>
ng-change call the given function each time the input change.
refresh() don't need a parameter because it use $scope.Reference

Angular.js accessing model from controller (server validation)

i now trying to migrate my legace app to Angular and now stuck with following issue.
I have this simple form:
<form name="loginForm" ng-controller="LoginCtrl" ng-submit="doLogin()">
<input type="text" name="login" ng-model="login.login" />
<span class="errors" ng-show="loginForm.login.$error.required">Required</span>
<span class="errors" ng-show="loginForm.login.$error.bad_login">Login or pass incorrect</span>
<input type="password" ng-model="login.pass"/>
</form>
Server returns error as this type of JSON: { login: 'bad_login', pass: 'incorrect' }
And in controller:
function LoginCtrl($scope, $http) {
$scope.doLogin = function() {
var model = $scope.login;
var req = { "login": model.login, "pass": model.pass };
$http({ method: "POST", url: "/login", data: req }).success(function (resp) {
if(resp.status != "ok") {
angular.forEach(resp, function (value, key) {
// ex: model['login'].$setValidity('bad_login', false);
model[key].$setValidity(value, false);
});
}
});
};
}
I try to mark each field in loop, not to hardcode every field by hand. but this approach not working. I get this error: TypeError: Cannot call method '$setValidity' of undefined, even when field is left empty i have another error: TypeError: Cannot read property 'login' of undefined
So i think i need to get instance of model for every field in form, any ideas ?
The reason it's coming back undefined is because unless you actually specify something for $scope.login.login or $scope.login.pass to begin with, they aren't set. If you put a space and delete it, you'll see they are set as blank. What you're going to want to do is at the beginning of your controller define the login on the scope like so:
function LoginCtrl($scope, $http) {
$scope.login = {
login: "",
pass: ""
};
$scope.doLogin = function() {
var req = { "login": $scope.login.login, "pass": $scope.login.pass };
$http({ method: "POST", url: "/login", data: req }).success(function (resp) {
if(resp.status != "ok") {
angular.forEach(resp, function (value, key) {
// ex: model['login'].$setValidity('bad_login', false);
$scope.login[key].$setValidity(value, false);
});
}
});
};
}

Categories