I'm trying to make a form that sends an url of the type /:id/:option where I know the id before entering the form but the option-attribute is the one that the user selects from the radio-buttons. After submitting the form I should move to the page /:id/:option. I'm also using angulasJS with my application.
So how can I send the url with the POST-method?
html
<form method="POST">
<div class="voteOptions" ng-repeat="item in id.data.options">
<label class="radioButtons">{{item.title}} votes:{{item.votes}}
<input type="radio" name="option" value={{item.option}}>
<span class="radioSelector"></span>
</label>
</div>
<input type="submit" id="voteSubmit" value="Vote!">
</form>
.post-call
app.post('/:id/:option', (req, res) => {
var poll = polls[req.params.id-1];
poll.options[req.params.option-1].votes++;
res.json(poll);
});
Create Controller and make Http call from there.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<form method="POST" ng-submit="submit()">
<div class="voteOptions" ng-repeat="item in options">
<label class="radioButtons">{{item.title}} votes:{{item.votes}}
<input type="radio" name="option" value={{item.option}} ng-model="option.val">
<span class="radioSelector"></span>
</label>
</div>
<input type="submit" id="voteSubmit" value="Vote!">
</form>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope,$http) {
var id = 12345;
$scope.option = {val:0};
$scope.options= [{
title : 'option-1',
votes : 5,
option : 1
},{
title : 'option-2',
votes : 5,
option : 2
}];
$scope.submit = function(){
console.log('Url', `<domain>/${id}/${$scope.option.val}`);
// Generate url and call http post
// $http.post(url, body, config)
// .success(function (data, status, headers, config) {
// })
// .error(function (data, status, header, config) {
// });
}
});
</script>
</body>
</html>
Related
How I can set val1 to $_POST variable ? Because in step 2 val1 is null.
I try to use $scope, $rootScope, angular.copy() and .val().
This is my html code:
<html ng-app="myApp"><body>
<form action="url.php" method="POST" ng-controller="FormController as vmForm">
<div ng-switch="vmForm.step">
<div class="stepone" ng-switch-when="one">
<label for="val1">Val1</label>
<input type="text" name="val1" ng-model="val1">
<button type="button" ng-click="vmForm.stepTwo()"></button>
</div>
<div class="steptwo" ng-switch-when="two">
<label for="val2">Val2</label>
<input type="text" name="val2" ng-model="val2">
<input type="submit" value="Submit">
</body>
JS
<script>
angular.module('myApp', ['ngAnimate'])
.controller('FormController', FormController);
function FormController($scope) {
var vm = this;
vm.step = "one";
vm.stepTwo = stepTwo;
function stepTwo() {
vm.step = "two";
}
}</script>
$_POST is a PHP variable that's accessible on the server. It contains the payload or request body that's sent in a HTTP POST request as an associative array. It cannot be set directly using Javascript / AngularJS.
What you can do is construct your request data and make a $http POST request to your form action endpoint. Here's a working example based on the code you posted: http://plnkr.co/edit/C1FGvoDrmzYEFMCwymIG?p=preview
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="myApp">
<h1>Hello Plunker!</h1>
<form ng-submit="formSubmit()" ng-controller="FormController">
<p>Val1: {{val1}}</p>
<p>Val2: {{val2}}</p>
<div ng-switch="vm.step">
<div class="stepone" ng-switch-when="one">
<label for="val1">Val1</label>
<input type="text" name="val1" ng-model="$parent.val1">
<button type="button" ng-click="stepTwo()">Go to Step two</button>
</div>
<div class="steptwo" ng-switch-when="two">
<label for="val2">Val2</label>
<input type="text" name="val2" ng-model="$parent.val2">
<input type="submit" value="Submit">
</div>
</div>
</form>
</body>
</html>
script.js
var app = angular.module('myApp', []);
app.controller('FormController', ['$scope','$http',function ($scope,$http) {
$scope.vm = {
step : "one"
};
$scope.val1 = "";
$scope.val2 = "";
$scope.stepTwo = function () {
$scope.vm.step = "two";
}
$scope.formSubmit = function () {
console.log($scope.val1, $scope.val2);
var req = {
url : 'url.php',
method: 'POST',
data : {
val1 : $scope.val1,
val2 : $scope.val2
}
};
$http(req).then(function(response) {
console.log('success', response);
}, function(errorResponse){
console.log('error', errorResponse);
});
}
}]);
Just leave everything as is in your controller and tweak your HTML like this:
<form action="url.php" method="POST" ng-controller="FormController as vmForm">
<div ng-switch="vmForm.step">
<div class="stepone" ng-switch-when="one">
<label for="val1">Val1</label>
<input type="text" name="val1" ng-model="vmForm.val1">
<button type="button" ng-click="vmForm.stepTwo()">Goto Step 2</button>
</div>
<div class="steptwo" ng-switch-when="two">
<input type="hidden" name="val1" value="{{vmForm.val1}}">
<label for="val2">Val2</label>
<input type="text" name="val2" ng-model="val2">
<input type="submit" value="Submit">
</div>
</div>
</form>
The tweak to your code is simply raising the scope of "val1" to "vmForm.val1" so in Step 2 "vmForm.val1" can be assigned to a hidden input field for posting.
Here's the form fields being posted in the browsers debugger:
Here's a Plunker, http://plnkr.co/edit/3VaFMjZuH09A4dIr1afg?p=preview
Open your browsers debugger and view network traffic to see form fields being posted.
i want to send a http get request which is not a problem.
But the problem is i want to disply the data from the server page. Does it has to be a JSON page to display the data from remote server ? or any sort of data can be displayed ? if yes , then how
Thank you
<div class="form" ng-app="myApp" ng-controller="myCtrl">
<p>Enter URL : <input type="text" ng-model="url" /></p>
<p><input type="submit" value="CHECK" ng-click="callAPI()" /> </p> <!-- 1 -->
<p>
<ul ng-repeat="post in posts">
<li>{{post}}</li>
</ul>
</p>
<div ng-bind="result"></div> <!-- 5 -->
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.callAPI = function() { // 2
//console.log($scope.url); //3
$http.get($scope.url)
.success(function(response) {
$scope.posts = response.data; //4
});
};
});
</script>
</body>
</html>
another version of code
<div class="form" ng-app="myApp" ng-controller="myCtrl">
<p>Enter URL : <input type="text" ng-model="url" /></p>
<p><input type="submit" value="CHECK" ng-click="callAPI()" /> </p>
<div ng-bind="result"></div> <!-- 5 -->
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.$watch('url', function() {
fetch();
});
function fetch() {
console.log($scope.url);
$http.get($scope.url)
.success(function(response) {
$scope.result = response.data;
});
}
$scope.callAPI= function() {
this.setSelectionRange(0, this.value.length);
}
});
</script>
</body>
</html>
Like the comments says, I believe that angular look at the content Type of the response to parse the data. Have you try added the accept header type?
What is the content type of the response?
var req = {
method: 'GET',
url: 'http://example.com',
headers: {
'Accept': change this to whatever content you want to accept
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});
hey i have found my answer of my question ...
there was a mistake in the source code
here is the right one
<div class="form" ng-app="myApp" ng-controller="myCtrl as controller">
<p>Enter URL : <input type="text" ng-model="url" /></p>
<p><input type="submit" value="CHECK" ng-click="clickButton()" /> </p>
<p>
<ul>
<li ng-repeat="data in result">
{{data}}
</li>
</ul>
</p>
</div>
and
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.clickButton = function() {
console.log($scope.url);
$http.get($scope.url)
.then(function(response) {
$scope.result = response.data;
});
};
});
</script>
:)
if anyone has a similer problem , i hope this answer will help ..
cheers
function functionName(){
$http.get(URL).success(function(response){
$scope.variable = response;
})
}
inside get() put your url, if your url returning any data then it will go to success() function.
This question already has answers here:
Share data between AngularJS controllers
(11 answers)
Closed 6 years ago.
I have a team_list page and a team page. A user will have a list of teams they are in in the team_list page and then click on one of the teams to go to its team page. I am not sure how to send the data that the team page that the user is going to is Team A's teampage or Team B's team page. So how do I share data between controllers?
I know I should be using services but I'm not sure how to use them in this context..I've tried some methods and commented out some but I'm still not sure how to go about this.
Using node.js and express framework for backend
team_list.html:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<head>
<title>Team List</title>
</head>
<body>
<h1>
Welcome to Your Team List Page!
</h1>
<!--<div ng-app="teamListPage" ng-controller="listController">
<fieldset>
<legend>Your Teams</legend>
<ul>
<li ng-repeat="x in [dave, david, darrell]">{{x}}</li>
<input type="button" id="enter" name="enter" value="Enter Home Page" ng-click="enterTeamPage()"/>
</ul>
</fieldset>
</div>-->
<div ng-app="teamListPage" ng-controller="listController">
<li ng-repeat="x in records">
{{x.team_name}}<br/>
<input type="button" id="enter" name="enter" value="Enter Home Page" ng-click="enterTeamPage()"/>
</li>
<input type="button" id="Create" name="Create" value="Create New Team" ng-click="enterCreateTeamPage()" />
</div>
<script>
var page = angular.module('teamListPage', []);
/*page.factory('myService', function() {
var user_id = [];
var setUserID = function(newObj) {
user_id.push(newObj);
};
var getUserID = function(){
return user_id;
};
return {
setUserID: setUserID,
getUserID: getUserID
};
});*/
page.factory('myService', function(){
return {
data: {
user_ID: ''
},
update: function(userID) {
// Improve this method as needed
this.data.user_ID = userID;
}
};
});
page.controller('listController', function($scope, $http, $window, myService) {
console.log(myService.data);
var login_http = $http({
method: 'GET',
url: '/team_req',
params: { user_id: 1 }
}).then(
function (response) {
//$window.alert(response.data[0].team_name);
$scope.records = response.data;
//console.log($scope.records[1]);
//alert('successfull ...');
}, function (response) {
$window.alert('wrong username/password');
}
)
$scope.enterTeamPage = function() {
$window.location.href = '/teamPage';
};
$scope.enterCreateTeamPage = function() {
$window.location.href = '/createTeamPage';
};
})
</script>
</body>
</html>
team_page.html:
<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<head>
<meta charset="UTF-8">
<title>Team Page</title>
</head>
<body>
<h1>
Team Page
</h1>
<div ng-app="teamPage" ng-controller="teamController">
<form id="Communication Board">
<fieldset>
<legend>COMMUNICATION BOARD</legend>
<h3>
chat feature coming up!
</h3>
<legend>videocall</legend>
<h4>
video call feature coming up!
</h4>
<legend>screenshare</legend>
<h5>
screenshare feature coming up!
</h5>
</fieldset>
</form>
<form id="Data Board" action="">
<fieldset>
<legend>DATA BOARD</legend>
<h6>
calendar feature coming up!
</h6>
<legend>announcements</legend>
<h7>
All features are coming up very soon!
</h7>
</fieldset>
</form>
<p>
<input type="button" id="CodingZone" name="CodingZone" value="Go to Coding Zone" ng-click="enterCodingPage()" />
</p>
</div>
<script>
var page = angular.module('teamPage', []);
page.controller('teamController', function($scope, $http, $window) {
//get the history of the chat board
$scope.getChatHistory = function() {
var create = $http({
method: 'Get',
url: '/chatHistory'
}).then(
function successful(response) {
$scope.theResponse = response.data;
}, function unsuccessful(response) {
alert('got an error back from server');
$scope.theResponse = response;
});
}
$scope.enterCodingPage = function() {
$window.location.href = '/codingPage';
};
})
</script>
</body>
</html>
Also should I put my service in app.js or index.js?
The best way to share data between controllers or components (wrappers for directives) is to use angular services and inject them into controllers. Cuz services are singletons so each of them presents single state for all components where it will be injected.
I am implementing AngularJS on an existing web application that requires a common HTTP POST like you would do without AngularJS.
Does any one have a work around to do that?
i have tried setting action="#" and action="." and just action and then do some jquery to inject a action like this. but nothing works
<script type="text/javascript">
$("form").get(0).setAttribute( "action", "test.html" );
</script>
HERE IS MY FORM AND CODE
//MY FORM
<form name="userForm" ng-submit="submitForm(userForm.$valid)" xt-form novalidate>
<div class="form-group">
<div class="col-sm-6" ng-class="{ 'has-error' : userForm.fornavn.$invalid && !userForm.fornavn.$pristine }">
<label class="control-label" for="textinput">Fornavn <span class="star-color">*</span></label>
<input autocomplete="off" type="text" value="<?php echo set_value('fornavn'); ?>" name="fornavn" ng-model="userFormData.fornavn" class="form-control" xt-validate msg-required="Du skal udfylde dit Fornavn" required>
</div>
<div class="col-sm-6" ng-class="{ 'has-error' : userForm.efternavn.$invalid && !userForm.efternavn.$pristine }">
<label class=" control-label" for="textinput">Efternavn <span class="star-color">*</span></label>
<input autocomplete="off" type="text" value="<?php echo set_value('efternavn'); ?>" name="efternavn" ng-model="userFormData.efternavn" class="form-control" xt-validate msg-required="Du skal udfylde dit Efternavn" required>
</div>
</div>
<button id="membership-box__payBtn" type="submit" ng-model="userFormData.betaling" name="betaling" class="btn btn-success text-uppercase">Gå til betaling</button>
</form>
//CODEIGNITER CONTROLLER
if (isset($_POST['betaling'])) {
$data['tilBetaling'] = array(
'oprettelse' => $this->input->post('oprettelse'),
// 'medlemskab' => $this->input->post('medlemskab'),
'tilBetaling' => str_replace(',', '.', $this->input->post('tilBetaling')),
'pr_maaned' => $this->input->post('pr_maaned'),
'start_date' => $this->input->post('start_date'),
'til_dato' => $this->input->post('til_dato'),
'pakke' => $this->input->post('pakke'),
'type' => $this->input->post('medlemskabTypeFinal'),
'getCenter' => $this->input->post('getCenter'),
'medlemskabPakkePID'=> $this->input->post('medlemskabPakkePID'),
'ekstraInput' => $this->input->post('ekstraInput'),
'periode_price' => $this->input->post('periode_price'),
'kampagneTag' => $this->input->post('kampagneTag'),
// 'header' => $this->input->post('header'),
);
//Gem array til session
$_SESSION['betaling'] = $data['tilBetaling'];
}
If you want to do a normal submit, you can handle ngClick in your controller:
HTML
<div ng-controller="ctrl">
<form name="userForm" action="user/add" method="post">
Name: <input name="name" ng-model="user.name" />
...
<button ng-click="onSubmit(userForm)">Submit</button>
</form>
</div>
JS
app.controller('ctrl', function($scope) {
$scope.onSubmit = function(form) {
if (form.$valid) {
var e = document.getElementsByName(form.$name);
e[0].submit();
}
}
});
An Alternative Solution
As an alternative, consider leveraging services, and redirecting after a successful POST in AngularJS.
HTML
<div ng-controller="ctrl">
<form name="userForm" ng-submit="onSubmit(user)">
Name: <input name="name" ng-model="user.name" />
...
<button type="submit">Submit</button>
</form>
</div>
JS
app.factory('UserService', function($http) {
return {
addUser: function(user) {
return $http({method:'POST', url:'api/user/add', data: user });
}
}
});
app.controller('ctrl', function($scope, $location, UserService) {
$scope.onSubmit = function(user) {
if ($scope.userForm.$valid) {
UserService.addUser(user).success(function() {
$location.path('/user/addSuccessful')
});
}
}
});
Even if you do an AngularJs submit, the request does not go to server. The control still remains on client side. Then you can post the data/form etc through $http service. You can inject $http service in your controller. as
app.controller('reviewCtrl', ['$http', function($http){
$scope.addReview = function(product){
//use $http service here
// Simple POST request example (passing data) :
$http.post(' / someUrl ', {msg:' hello word!'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
}]);
note: please review the syntax before running the code.
To submit the Angular Js form ONLY after Angular validations are through or passed, you must use reviewForm.$valid flag chack in ng-submit.
With this flag check, the form will not get submitted until all validations are passed.
<form name="reviewForm" ng-controller="reviewCtrl" ng-submit="reviewForm.$valid && reviewCtrl.addReview(product)" novalidate>
....
....
</form>
Currently, I am using a server side framework CakePHP to build my app.
I need to integrate angular into my app.
Currently, I send the following inputs
User.old_password, User.new_password, User.new_password_confirm
to this url /mypasswords/new using POST
This works just fine.
I understand that to send data to server side I need to use services in Angular.
This is my Angular code so far.
var app = angular.module("myApp", []);
app.controller('passwordController', ['$scope', function($scope) {
$scope.submitted = false;
$scope.changePasswordForm = function() {
if ($scope.change_password_form.$valid) {
// Submit as normal
} else {
$scope.change_password_form.submitted = true;
}
}
}]);
services = angular.module('myApp.services', ['ngResource']);
services.factory("UserService", function($http, $q) {
var service;
// service code here
});
So what do I write in the //service code here part? What other parts am I missing?
My form currently looks like this as html after being rendered. (I know I probably have to remove action and method attributes from my form. Do I?)
<form action="/mypasswords/new" id="change_password_form" name="change_password_form" ng-controller="passwordController" ng-submit="changePasswordForm()" method="post" accept-charset="utf-8" class="ng-scope ng-pristine ng-valid">
<div style="display:none;"><input type="hidden" name="_method" value="POST"></div>
<input name="data[User][old_password]" id="u56" placeholder="Enter old password..." class="u56 profile_input" type="password">
<input name="data[User][new_password]" id="u57" placeholder="Enter new password..." class="u57 profile_input" type="password">
<input name="data[User][new_password_confirm]" id="u58" placeholder="Enter new password..." class="u58 profile_input" type="password">
<div id="u25" class="u25_container">
<div id="u25_img" class="clear_all_button detectCanvas" onclick="document.getElementById('change_password_form').reset()">
</div>
</div>
<div id="u27" class="u27_container">
<input id="u27_img" class="submit_button detectCanvas" type="submit" value="SAVE">
</div>
</form>
Thank you.
if you want just to send the form with ajax, No need to create factory, just do it in controller like this:
var app = angular.module("myApp", [$http]);
app.controller('passwordController', ['$scope', function($scope) {
$scope.submitted = false;
$scope.changePasswordForm = function() {
if ($scope.change_password_form.$valid) {
//note: use full url, not partial....
$http.post('http://myweb.com/mypasswords/new', change_password_form.Data)
.success(function(data, status, headers, config) {
//do anything when it success..
})
.error(function(data, status, headers, config){
//do anything when errors...
});
} else {
$scope.change_password_form.submitted = true;
}
}
}]);
And your form will looks like this:
<form id="change_password_form" name="change_password_form" ng-controller="passwordController" ng-submit="changePasswordForm()" method="post" accept-charset="utf-8" class="ng-scope ng-pristine ng-valid">
<div style="display:none;"><input type="hidden" name="_method" value="POST"></div>
<input name="data[User][old_password]" ng-model="Data.old_password" id="u56" placeholder="Enter old password..." class="u56 profile_input" type="password">
<input name="data[User][new_password]" ng-model="Data.new_password" id="u57" placeholder="Enter new password..." class="u57 profile_input" type="password">
<input name="data[User][new_password_confirm]" ng-model="Data.new_password_confirm" id="u58" placeholder="Enter new password..." class="u58 profile_input" type="password">
<div id="u25" class="u25_container">
<div id="u25_img" class="clear_all_button detectCanvas" onclick="document.getElementById('change_password_form').reset()">
</div>
</div>
<div id="u27" class="u27_container">
<input id="u27_img" class="submit_button detectCanvas" type="submit" value="SAVE">
</div>
</form>
Step 1: write form using normal html instead of FormHelper in CakePHP
The form should look like this:
<form name="change_password_form" ng-controller="passwordController"
ng-submit="changePasswordForm()">
<input name="data[User][old_password]" ng-model="data.User.old_password" type="password" placeholder="Enter old password..." class="u56 profile_input">
<input name="data[User][new_password]" ng-model="data.User.new_password" type="password" placeholder="Enter new password..." class="u57 profile_input">
<input name="data[User][new_password_confirm]" ng-model="data.User.new_password_confirm" type="password" placeholder="Enter new password again..." class="u58 profile_input">
<div id="u25"
class="u25_container">
<div id="u25_img"
class="clear_all_button detectCanvas" onclick="document.getElementById('change_password_form').reset()">
</div>
</div>
<div id="u27"
class="u27_container">
<button type="submit" id="u27_img" ng-click="debug()"
class="submit_button detectCanvas" />
</div>
</form>
Step 2: write the app.js in the following manner.
the X-Requested-With header is important if you want to use the CakePHP $this->request->is('ajax')
angular.module("myApp", [])
.controller('passwordController', function($scope, $http) {
$scope.changePasswordForm = function() {
console.log('change passwrd form activated');
//note: use full url, not partial....
$http({
method : 'POST',
url : '/mypasswords/new',
data : $.param($scope.data), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With' : 'XMLHttpRequest'
} // set the headers so angular passing info as form data (not request payload)
})
.success(function(data, status, headers, config) {
//do anything when it success..
console.log('works!');
})
.error(function(data, status, headers, config){
//do anything when errors...
console.log('errors!');
});
}
$scope.debug = function () {
console.log($scope);
}
});