Putting value to hidden input and then getting it in POST variable - html

I am trying to get an input value with AngularJS from input field to another hidden input field (in another form in the same page) so I can transmit it later if user presses submit on the other form.
<div ng-app="">
<p>Name: <input type="text" ng-model="name"></p>
//down the code...
<form name="whatever" method="post">
<input type="hidden" ng-bind="name" value="">
</form>
</div>
When I inspect the code after I put data in the visible input field all looks fine - so when I change the data inside the visible input I can see it in the hidden input too but I can't see it in the POST variable after I submit the form - I guess it's because it doesn't change the value field in the hidden input just what between the and .
How can I get this to work so that I change the value of an hidden input - but not what between the opening and closing input field?

Just Replace ng-bind with ng-value like:
<input type="hidden" ng-value="name">
(Credit to Himmet Avsar)

I see you answered yourself already. Anyway you should go for more "angular way" when handling your forms, letting angular do the "posting". For example:
HTML template
<body ng-controller="MainCtrl">
<form name="form1"
ng-submit="submit()">
Name: <input type="text"
class="form-control"
name="name"
ng-model="user.name"
required>
<div class="alert alert-warning"
ng-show="form1.name.$error.required">
Required field
</div>
<input type="submit"
class="btn btn-primary"
value="submit">
</form>
<div class="alert"
ng-class="{ 'alert-success': response.status === 200, 'alert-danger': response.status !== 200 }"
ng-show="response !== null">
DATA: {{ response.data }}<br>
HTTP {{ response.status }} {{ response.statusText }}
</div>
<hr>
<form name="form2" ng-submit="submit()">
Name: <input type="text"
class="form-control"
ng-model="user.name">
Age: <input type="number"
class="form-control"
min="1"
max="100"
ng-model="user.age">
<input type="submit"
class="btn btn-primary"
value="submit" disabled>
</form>
</body>
JavaScript
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $http) {
$scope.user = {};
$scope.response = null;
$scope.submit = function() {
$scope.response = null;
$http({
method: 'POST',
url: 'http://jsonplaceholder.typifcode.com/posts',
data: $scope.user,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (response) {
$scope.response = response;
}).catch(function (response) {
$scope.response = response;
});
};
});
You'll get something like
Related plunker here http://plnkr.co/edit/M7zQzp

Related

How to select a button without validating form

How do I prevent the form from checking the required field when I select the "Average Household Income" button.
<form method="post"> The
<input type="text" name="myIncome[0][Income]" required
placeholder="#######.##" pattern="^(?=.*[1-9])\d*(?:\.\d{2}$)?" />
<input type="submit" name='cmdSubmit' value="Submit"
formaction="ProjectCensus.php">
<input type="submit" name='cmdAvgHousehold' value="Average Household Income"
formaction="Average_household.php">
You would want to change the type on that button.
Try:
<button type="button" ... ></button>
Updated as per request:
I recommend you use JQuery ajax() for handling the submitting of the form (it will be the easiest to understand).
$("#myForm").submit(ev => {
ev.preventDefault();
$.ajax({
type: 'POST',
url: "Average_household.php",
// data: {},
success: resp => {
alert("Submitted comment");
},
error: resp => {
alert("There was an error submitting this form");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- src: https://html.com/attributes/button-type/ -->
<form id="myForm" action="/button-type">
<button type="button" onclick="alert('This button does nothing.')">Click me for no reason!</button>
<br><br>
<label for="name">Name</label><br>
<input name="name"><br><br> <button type="reset">Reset the form!</button><br><br>
<button type="submit" disabled>Submit (disabled)</button>
</form>
Hope this helps,

Redirecting to a page after submitting form in HTML

I'm fairly new to coding in HTML. After hours of searching the internet for a way to do this, I failed and so I'm here. I was setting up a CSRF Proof of concept page here, I want it to redirect to another page which will execute the payload that the CSRF had implemented.
<html>
<body>
<form action="https://website.com/action.php?" method="POST">
<input type="hidden" name="fullname" value="john" />
<input type="hidden" name="address" value="street 2, 32 ave" />
<input type="submit" value="Submit request" />
</form>
</body>
</html>
So after this form is submitted using, all it does is redirect to this page
But instead of that, I want it to redirect to another URL as well as submit that form.
For anyone else having the same problem, I figured it out myself.
<html>
<body>
<form target="_blank" action="https://website.com/action.php" method="POST">
<input type="hidden" name="fullname" value="Sam" />
<input type="hidden" name="city" value="Dubai " />
<input onclick="window.location.href = 'https://website.com/my-account';" type="submit" value="Submit request" />
</form>
</body>
</html>
All I had to do was add the target="_blank" attribute to inline on form to open the response in a new page and redirect the other page using onclick on the submit button.
You need to use the jQuery AJAX or XMLHttpRequest() for post the data to the server. After data posting you can redirect your page to another page by window.location.href.
Example:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
window.location.href = 'https://website.com/my-account';
}
};
xhttp.open("POST", "demo_post.asp", true);
xhttp.send();
in case you are generating the form programmatically you can add this script at the end of the form
<script type="text/javascript">document.forms["FormId"].submit();</script>
What you could do is, a validation of the values, for example:
if the value of the input of fullanme is greater than some value length and if the value of the input of address is greater than some value length then redirect to a new page, otherwise shows an error for the input.
// We access to the inputs by their id's
let fullname = document.getElementById("fullname");
let address = document.getElementById("address");
// Error messages
let errorElement = document.getElementById("name_error");
let errorElementAddress = document.getElementById("address_error");
// Form
let contactForm = document.getElementById("form");
// Event listener
contactForm.addEventListener("submit", function (e) {
let messageName = [];
let messageAddress = [];
if (fullname.value === "" || fullname.value === null) {
messageName.push("* This field is required");
}
if (address.value === "" || address.value === null) {
messageAddress.push("* This field is required");
}
// Statement to shows the errors
if (messageName.length || messageAddress.length > 0) {
e.preventDefault();
errorElement.innerText = messageName;
errorElementAddress.innerText = messageAddress;
}
// if the values length is filled and it's greater than 2 then redirect to this page
if (
(fullname.value.length > 2,
address.value.length > 2)
) {
e.preventDefault();
window.location.assign("https://www.google.com");
}
});
.error {
color: #000;
}
.input-container {
display: flex;
flex-direction: column;
margin: 1rem auto;
}
<html>
<body>
<form id="form" method="POST">
<div class="input-container">
<label>Full name:</label>
<input type="text" id="fullname" name="fullname">
<div class="error" id="name_error"></div>
</div>
<div class="input-container">
<label>Address:</label>
<input type="text" id="address" name="address">
<div class="error" id="address_error"></div>
</div>
<button type="submit" id="submit_button" value="Submit request" >Submit</button>
</form>
</body>
</html>
For me this one worked pretty well.
=> form target to blank (opens in a new tab) + input id to be recognized in Javascript + script that redirects.
<html>
<body>
<form target="_blank" action="https://website.com/action.php" method="POST">
<input type="hidden" name="fullname" value="Sam" />
<input type="hidden" name="city" value="Dubai " />
<input type="submit" value="Submit request" id="submitBtn"/>
<script>
document.getElementById("submitBtn").addEventListener("click", myFunction);
function myFunction() {
window.location.href="http://programminghead.com";
}
</script>
</form>
</body>
</html>
I found it here: https://programminghead.com/submit-button-redirect-to-another-page-in-html

Transfer table row data to html form page in angular

Using Angular JS I am trying to pass the data in a table row that is populated dynamically to an html page. The page would then use that object
that is passed to populate form data.
My html looks like below:
<form data-ng-submit="submit()" name="empRegForm" method="post">
<input type="hidden" type="text" ng-model="employee.employeeId" />
<fieldset class="table-striped">
<input placeholder="Employee Project Id" type="text" ng-model="employee.projectId" tabindex="1" required autofocus>
</fieldset>
<fieldset>
<input placeholder="Employee Name" type="text" ng-model="employee.employeeName" tabindex="2" required>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit">Submit</button>
</fieldset>
</form>
Method that I have created on the controller is as follows:
$scope.updateEmployee = function(employee) {
var response = $http.put('localhost:8080/employeeManagement/employee', employee);
response.success(function(data, status, headers, config) {
$scope.result = data;
});
response.error(function(data, status, headers, config) {
alert( "Exception details: " + JSON.stringify({data: data}));
});
};
EmployeeList html table appears as below:
<tr ng-repeat="employee in result.listOfEntities">
<td>{{employee.employeeId}}</td>
<td>{{employee.employeeName}}</td>
<td><a ng-click="updateEmployee(employee)"> <span class="fa fa-pencil-square-o" aria-hidden="true"></span></a></td>
</tr>
I want to redirect the page to the Update html page that contains the form when this button on the row is clicked.
Thanks
Added ng-include to load different html page in your table page itself and to toggle it on need basis as like example below,
In controller:
$scope.loadEmployee = function(employee){
$scope.employee=employee;
$scope.employee.visible=true;
};
$scope.updateEmployee = function(employee) {
var response = $http.put('localhost:8080/employeeManagement/employee', employee);
response.success(function(data, status, headers, config) {
$scope.result = data;
});
response.error(function(data, status, headers, config) {
alert( "Exception details: " + JSON.stringify({data: data}));
});
$scope.employee.visible=false;
};
In Template:
<tr ng-repeat="employee in result.listOfEntities">
<td>{{employee.employeeId}}</td>
<td>{{employee.employeeName}}</td>
<td><a ng-click="loadEmployee(employee)"> <span class="fa fa-pencil-square-o" aria-hidden="true"></span></a></td>
</tr>
<div ng-include src="'/employee-update.html'" ng-controller="employeeController" ng-show="employee.visible"></div>
employee-update.html:
<form data-ng-submit="updateEmployee()" name="empRegForm" method="post">
<input type="hidden" type="text" ng-model="employee.employeeId" />
<fieldset class="table-striped">
<input placeholder="Employee Project Id" type="text" ng-model="employee.projectId" tabindex="1" required autofocus>
</fieldset>
<fieldset>
<input placeholder="Employee Name" type="text" ng-model="employee.employeeName" tabindex="2" required>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit">Submit</button>
</fieldset>
</form>

how to validate particular input field using angularjs?

I am trying to validate some input fields using angularJS. I found some example. But they are validating entire form.
<div ng-app="myApp" ng-controller="myCtrl">
<form name="myform">
<input type="text" ng-model='name' ng-required="true" />
<input type="password" ng-model='password' ng-required="true" />
<button ng-click="myform.$valid && preview()">Preview</button>
<button ng-click="myform.$valid && update()">Update</button>
</form>
</div>
and controller code is
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name=undefined;
$scope.preview = function(){
alert("Previewed");
};
$scope.update = function(){
alert("Updated");
}
});
The above code validating the fields based on form name. But I wanted to know is there any way to validate that particular input field ?
DEMO
Yes you can, you must specify a name for the input like
<div ng-app="myApp" ng-controller="myCtrl">
<form name="myform">
<input type="text" name='name' ng-model='name' ng-required="true" />
<input type="password" ng-model='password' ng-required="true" />
<button ng-click="myform.$valid && preview()">Preview</button>
<button ng-click="myform.$valid && update()">Update</button>
</form>
</div>
then you can check if the name is valid with myForm.name.$valid
Check out the fiddle here.
Just add a name to the input filed and follow the same as you did to the form.
HTML:
<div ng-app="myApp" ng-controller="myCtrl">
<form name="myform">
<input type="text" ng-model='name' ng-required="true" name="txtName" />
<input type="password" ng-model='password' ng-required="true" />
<button ng-click="myform.$valid && preview()">Preview</button>
<button ng-click="myform.$valid && update()">Update</button>
<div>Status of name: <span style="color: blue">{{myform.txtName.$valid}}</span></div>
</form>
</div>
JS:
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.name = undefined;
$scope.preview = function () {
alert("Previewed");
};
$scope.update = function () {
alert("Updated");
}
});

Send JSON from HTML form with NODEJS backend

I haven't done front end HTML since I was 10 and that was drag and drop frontpage stuff. with static pages. As a result I'm really rusty.
What I need to do is put together a web client for a rest API that I wrote in NodeJS. My question is how, do you send a request from a form (say a log in form) to the server where the body of the POST request is a JSON of the email/password?
HTML form:
<form id="loginForm" action="" method="" class="form-horizontal">
<fieldset>
<legend>Log in</legend>
<div class="control-group">
<label class="control-label" for="email">Email</label>
<div class="controls">
<input type="text" class="input-xlarge" id="email">
</div>
</div>
<div class="control-group">
<label class="control-label" for="password">Password</label>
<div class="controls">
<input type="password" class="input-xlarge" id="password">
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Save changes</button>
<button class="btn">Cancel</button>
</div>
</fieldset>
</form>
I suggest a lot of reading. To get you started with a very basic example, though, you will find a page with a sample form below that does what you need. You just need to replace the string your URL here with the actual URL you expect will be doing the handling.
The serializeObject() function was taken from here: Convert form data to JavaScript object with jQuery
<html>
<body>
<form id="loginForm" action="" method="">
Username: <input type="text" name="username" id="username" /> <br />
Password: <input type="password" name="password" id="password" /> <br />
<input type="submit" />
</form>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(function () {
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$("#loginForm").bind("submit", function(evt) {
console.log(JSON.stringify($("#loginForm").serializeObject()));
$.ajax({
url: "your URL here",
type: "POST",
contentType: "application/json",
data: JSON.stringify($("#loginForm").serializeObject()),
success: function (data, textStatus, jqXHR) {
// do something with your data here.
},
error: function (jqXHR, textStatus, errorThrown) {
// likewise do something with your error here.
}
});
return false;
});
});
</script>
</body>
</html>
The problem with your form is that input elements don't have name attributes. The name attribute is essential in many ways, so I would fix your html by setting each element's name attribute to the same value as its id attribute. The serializeObject function relies on form elements having names.
Here's an example using jQuery:
<form name="myform" action="#" method="POST">
Username: <input type="text" id="user" name="username"/><br/>
Password: <input type="password" id="pass" name="password"/>
<input type="submit" id="login" value="Login"/>
</form>
<script type="text/javascript">
var user=$('#user').val(), pass=$('#pass').val();
$('login').bind('click', function() {
$.ajax('/my/url', {
type: 'POST',
contentType: 'text/json',
data: JSON.stringify({username:user, password:pass}),
complete: function() { /* Do something with the response. */ }
});
return false; // Prevent form submit.
});
</script>
This might help you. Here is the form below: If you notice there is action and method if you don't know what these are, just go on and search for it. Action is the target server file that handles the information you send and method is get which is retrieving not updating.
Existing Users Username: Password:
Keep Me
Logged In
Here is the jquery part to handle the ajax call:
$.ajax({
type: "GET",
url: action,
data: form_data,
success: function(response)
{
if($.trim(response) == 'success')
window.location.replace("profile.php");
else
$("#result").html(response);
}
});
return false; });
});