Formatting JSON data from iron-form - json

I'm using iron-form to send data to a Rails server. Currently the form is sending JSON similar to this:
{
"date": "January 1",
"name": "John Doe",
"company": "Whatever Inc."
}
But in order to receive it on the Rails end I need it to be formatted like this:
{
"userInfo": {
"date": "January 1",
"name": "John Doe",
"company": "Whatever Inc."
}
}
How do I nest the form data within the userInfo param? I tried using the iron-form-presubmit event listener but couldn't make it work.
Here is the code for my iron-form:
<form is="iron-form" id="form" method="post" action="url/for/api">
<input name="date" is="iron-input">
<input name="name" is="iron-input">
<input name="company" is="iron-input">
<div id="buttons">
<paper-button id="submit" raised onclick="_submit(event)">Save</paper-button>
<paper-button id="reset" raised onclick="_reset(event)">Reset </paper-button>
</div>
</form>
And the javascript:
<script>
Polymer({
is: 'my-view1',
});
function _submit(event) {
var form = Polymer.dom(event).localTarget.parentElement.parentElement;
form.submit();
}
function _reset(event) {
var form = Polymer.dom(event).localTarget.parentElement.parentElement;
form.reset();
}
</script>

from my understanding you could update the request body before the data gets submitted and transform the current data into an object/structure of your liking:
<form is="iron-form" on-iron-form-presubmit="_presubmit" id="form" method="post" action="url/for/api">
<input name="date" is="iron-input">
<input name="name" is="iron-input">
<input name="company" is="iron-input">
<div id="buttons">
<paper-button id="submit" raised onclick="_submit(event)">Save</paper-button>
<paper-button id="reset" raised onclick="_reset(event)">Reset </paper-button>
</div>
</form>
similar to how its done here, but changing the body entirely
function _presubmit(e) {
let body = this.$.form.request.body;
body = {"userInfo" : body };
}
Hope this helps a lil.

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,

How to send data to HTML page and how to use AJAX for Single Page Application in NodeJS Server using express.js framework?

How can I display the form submitted data in another HTML Page
From 1st page (page1.html)collecting the data from users and after appending this data in the database I want to show the submitted values in another page i.e.(page4.html)
Below is my code
I have tried using res.sendFile or res.send
server.post('/addname', (req, res) => {
const user = {
timestamp: new Date,
FName: req.body.FName,
LName: req.body.LName,
Phone: req.body.Phone,
Email: req.body.email,
Contact: req.body.business,
Business: req.body.contact,
OTP: req.body.otp_field
}
res.sendFile(__dirname + '/page4.html');
//along with file rediraction, how can i send or show the "User" vaules in respactivte filed
});
<body>
<div>
<div align="center">
<form action="/addname" method="GET">
<label>Please enter below details</label><br><br>
<label>First Name *: </label><input id="FName" type="text" name="FName"/><br><br>
<label>Last Name *: </label><input id="LName" type="text" name="LName"/><br><br>
<label>Email Address *: </label><input type="email" name="email"><br><br>
<br><br>
<input type="submit" value="Submit" /></form>
</div>
</div>
</body>
nAs I can see in your code
<body>
<div>
<div align="center">
<form action="/addname" method="GET">
<label>Please enter below details</label><br><br>
<label>First Name *: </label><input id="FName" type="text" name="FName"/><br><br>
<label>Last Name *: </label><input id="LName" type="text" name="LName"/><br><br>
<label>Email Address *: </label><input type="email" name="email"><br><br>
<br><br>
<input type="submit" value="Submit" /></form>
</div>
</div>
</body>
Your form method is "GET", it should be "POST" as your API is "POST".
server.post('/addname', (req, res) => {
<form action="/addname" method="GET">
//Just change to
<form action="/addname" method="POST">
While sending and HTML file you need to send your submitted data too.
res.sendFile(__dirname + '/page4.html');
In order to save your hurdle switch to Single Page Application and use some JavaScript frame work like AngularJs, ReactJs or if not then also stick to single page and use Ajax calls for submit calls.
Else see "ejs" in place of "HTML" and use scriptlet to send and show data over HTML.
To send data to "ejs" via expressJs
res.render('show.ejs', {message});
With Ajax you can do this:
HTML
<body>
<div>
<div align="center">
<form id="form1">
<label>Please enter below details</label><br><br>
<label>First Name *: </label><input id="FName" type="text" name="FName"/><br><br>
<label>Last Name *: </label><input id="LName" type="text" name="LName"/><br><br>
<label>Email Address *: </label><input type="email" name="email"><br><br>
<br><br>
<input type="button" value="Submit" onClick:"submitForm()"/>
</form>
<div id="showValue"></div>
</div>
</div>
</body>
JavaScript
function submitForm() {
$.ajax({
url: '/addName',
type: 'POST',
headers: headers,
data: {
"Fname": $("#FName").val(),
"Lname": $("#LName").val(),
"email": $("#email").val()
},
success: function(result) {
//append result to your html
//Dynamic view
$("#form1").hide();
var html = '<div><span>First Name: ' + result.fName + '</span><span>Last Name: ' + result.lName + '</span></div>';
$("#showValue").html(html);
},
error: function (error) {
alert('error ',error);
}
});
}
Server side code I'm assuming you are using express.js and body-parser
app.post('/addName', (req, res) => {
//Insert into db
var body = req.body;
res.send({
fName: body.FName,
lName: body.LName
});
});

Form submit to a text field

How to make a form that submit to a text field below
<form action="">
Text: <input type="text" name="firstname">
<input type="submit" value="Submit"><br><br>
Post text: <input type="text" name="firstname">
</form>
You will need to use JavaScript for that:
<script>
function submitted() {
formValue = document.getElementsByName("firstname")[0].value;
document.getElementsByName("firstname")[1].setAttribute("value", formValue); // Copy the value
return false;
}
</script>
<form onsubmit="return submitted()"> <!-- Call submitted when the form is submitted -->
Text: <input type="text" name="firstname">
<input type="submit" value="Submit"><br><br> Post text: <input type="text" name="firstname">
</form>
However, there is no need for a form for that. The onsubmit attribute is mostly used for when you want to alert the user that the form was submitted; the actual submission is done on the server through PHP or something else, and not through JavaScript (since the user has access to the JavaScript code and could change the input checking process as he wishes). Here you could simply have something like this:
<script>
function submitted() {
formValue = document.getElementById("firstname").value;
document.getElementById("postFirstname").setAttribute("value", formValue); // Copy the value
}
</script>
Text: <input type="text" id="firstname">
<button onclick="submitted()">Submit</button>
<br><br> Post text: <input type="text" id="postFirstname">

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

Node.js body-parser won't parse input names with square brackets in json

I have a problem with Express body-parser in Node.js
I have inputs like this:
<input id="personEmail1" type="email" name="person[0][email]" placeholder="Email1" class="form-control">
<input id="personEmail2" type="email" name="person[1][email]" placeholder="Email2" class="form-control">
After when I submit my form I got this in my console.log:
{ 'person[0][email]': 'info#sss.sss', 'person[1][email]': 'info#ggg.ggg' }
But I want it to be parsed in json format:
{ person: [{email: 'info#sss.sss'}, {email: 'info#ggg.ggg'}] }
What I'm doing wrong?
for express version 4.x when you need to manually install body-parser and multer, and you want to get nested properties from the post, e.g. data[test] in the form of req.body.data.test, you need to set:
app.use(bodyParser.urlencoded({ extended: true }));
Even though you've used valid Javascript syntax for your keys, they are still just strings and no JSON parser will attempt to call eval on them.
However, JSON already has a concept of arrays, which should work in the way you are expecting them to.
It would be useful to show us the code in which the call to console.log happens. But I would guess that instead, you need to rethink the naming convention for your field names.
<input id="personEmail1" type="email" name="personEmail1" placeholder="Email1" class="form-control">
<input id="personEmail2" type="email" name="personEmail2" placeholder="Email2" class="form-control">
Then create the Javascript object from that data.
function handler(req, res) {
var people = [
{ email: req.body.personEmail1 },
{ email: req.body.personEmail2 }
];
console.log(people[0]); // person 1
console.log(people[1]); // person 2
console.log(people); // both people
}
You are using the Express body-parser middleware bracket notation correctly. But, as an example of what can be done...
Using this view:
<form method="post">
<label for="person_email_1">Email address 1</label>
<input id="person_email_1" name="person[0][email]" type="email" value="email1#example.com"> <br>
<label for="person_email_2">Email address 2</label>
<input id="person_email_2" name="person[1][email]" type="email" value="email2#example.com"> <br>
<button type="submit">Submit v1</button>
</form>
<br>
<form method="post">
<label for="person_email_1">Email address 1</label>
<input id="person_email_1" name="person[email][0]" type="email" value="email1#example.com"> <br>
<label for="person_email_2">Email address 2</label>
<input id="person_email_2" name="person[email][1]" type="email" value="email2#example.com"> <br>
<button type="submit">Submit v2a</button>
</form>
<br>
<form method="post">
<label for="person_email_1">Email address 1</label>
<input id="person_email_1" name="person[email]" type="email" value="email1#example.com"> <br>
<label for="person_email_2">Email address 2</label>
<input id="person_email_2" name="person[email]" type="email" value="email2#example.com"> <br>
<button type="submit">Submit v2b</button>
</form>
<br>
<form method="post">
<label for="person_email_1_address">Email address 1</label>
<input id="person_email_1_address" name="person[emailAddresses][0][address]" type="email" value="email1#example.com">
<input id="person_email_1_description" name="person[emailAddresses][0][description]" type="text" value="lorem ipsum 1"> <br>
<label for="person_email_2_address">Email address 2</label>
<input id="person_email_2_address" name="person[emailAddresses][1][address]" type="email" value="email2#example.com">
<input id="person_email_2_description" name="person[emailAddresses][1][description]" type="text" value="lorem ipsum 2"> <br>
<button type="submit">Submit v3</button>
</form>
...and this post handler:
function postHandler(req, res) {
console.log(JSON.stringify(req.body)); // show in console
res.send(req.body); // show in browser
}
Version 1 (your version, which works for me, and returns your desired result) req.body:
{
"person": [
{"email": "email1#example.com"},
{"email": "email2#example.com"}
]
}
Versions 2a & 2b (an array of strings, with/without index number) req.body:
{
"person": {
"email": [
"email1#example.com",
"email2#example.com"
]
}
}
Version 3 (an array of objects) req.body:
{
"person": {
"emailAddresses": [
{
"address": "email1#example.com",
"description": "lorem ipsum 1"
},
{
"address": "email2#example.com",
"description": "lorem ipsum 2"
}
]
}
}
I've personally used versions 2 & 3 on a node/Express/jquery/Bootstrap line of business app where a person or business account can have unlimited telephone numbers, email addresses, and URLs. The body-parser bracket notation made it stupid easy.
I used this https://github.com/macek/jquery-serialize-object to serialize my form as JSON. It parses data as I want and it's easy to use.
$.ajax({
type: 'post',
data: $form.serializeJSON(),
contentType: 'application/json',
url: $url,
success: function (result) { ... }
});
I think this is the easyest