associating HTML form fields - html

How do I link multiple input elements in a form so the server knows that two values are related?
Let's assume we have separate fields for first and last names, for multiple people on a single page:
<input name="firstNames" value="John">
<input name="lastNames" value="Smith">
...
<input name="firstNames" value="Jane">
<input name="lastNames" value="Doe">
When POSTing that, the server eventually has the following data:
firstNames = ["John", "Jane"]
lastNames = ["Smith", "Doe"]
So we can determine the respective names by index:
person = firstNames[i] + lastNames[i]
Is there a better way than relying on the order? (Is that even reliable?)

EDIT : This is language specific
Upon further searching, some languages (ASP) allow you to get at the data as a CSV string. So you'll need to add further context to your question. However, the array method still works in all languages.
You can't rely on the order in PHP. If two HTML form elements have the same name the last one overrides everything else (in PHP at least).
Just use arrays.
<input name="firstNames[0]" value="John">
<input name="lastNames[0]" value="Smith">
...
<input name="firstNames[99]" value="Jane">
<input name="lastNames[99]" value="Doe">
You could also use empty [] empty braces as well.
EDIT
Copy paste the code below to see the behavior in PHP.
Down voters : I'd really be interested in knowing where this would not be the case (in a different language)
<html>
<head>
</head>
<body>
<form action='test.php' method='post'>
<input name="firstNames" value="John">
<input name="lastNames" value="Smith">
<input name="firstNames" value="Jane">
<input name="lastNames" value="Doe">
<input type='submit' value='Go'>
</form>
</body>
</html>
<?php
if (!empty($_POST)) {
var_dump($_POST);
}

Related

Fetch HTML Service Values by ID

In the sample code:
HTML (Index):
<form>
<br><br>
Name:
<br>
<input type="text" name="name">
<br><br>
Comments:
<br>
<input type="text" id="comments">
<br><br>
<input type="button" id="button" value="Submit Info" onclick="google.script.run
.testFunction(this.form)">
</form>
Code:
function doGet() {//Creates the webpage
return HtmlService.createTemplateFromFile('Index')//From the GUI file.
.evaluate()
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function testFunction(form){
Logger.log(form.name);//Works when using the 'name' of the element.
Logger.log(form.comments);//Does not work when using the 'ID'.
}
Why does a value get returned when adding the 'Name' of the HTML value, but not the 'ID'? If I want to get the value by ID, how would I do this instead? I've tried:
form.getElementById("comments");
But this just throws me an error, and to be honest I'm out of ideas after that.
Note: It's completely acceptable to me to use the 'name' field, as I have been doing, I'm just curious as I'm brushing up on my HTML.
I believe what Google is doing behind the scenes is extracting the form out as a HTML form and sending it back to the server. HTML forms use the name attribute to store all their name value pairs when sent back to the server. So if this was a get request for this form:
<form>
<input type="text" name="field1" value="value1"/>
<input type="text" name="field2" value="value2"/>
</form>
it would look something like ?field1=value1&field2=value2.
So on the server side in your Code.gs you are basically getting this back as an object (not a DOM object, which is why your form.getElementById("comments"); won't work).
Either way, the standard with <input> tags is to use the name attribute, so you should be sticking with that. The id attribute should really only be used if you need to look up a value in your client side javascript.

Do input names have to be unique in the same form?

I have a form with multiple fieldsets. Each fieldset has multiple inputs, some of which would logically share a name attribute.
I have looked on MDN for input name and the HTML 5 spec with no luck. Section 4.10.19.1 of the HTML 5 form spec does not mention a uniqueness requirement though.
For example:
<fieldset name="attendee">
<input name="full-name">
</fieldset>
<fieldset name="next-of-kin">
<input name="full-name">
</fieldset>
Each input name is unique within the fieldset, but duplicated within the form. Is this valid?
No, the name attributes are not required to be unique. You could have the name attribute similar in multiple input fields (the whole principle behind radio buttons for example). Modern browsers generally see an array of information when you are submitting the form. I will give you an example in which I used PHP to parse the information, but the point stands in other programming languages.
Given your example:
<fieldset name="attendee">
<input name="full-name">
</fieldset>
<fieldset name="next-of-kin">
<input name="full-name">
</fieldset>
If you var_dump() depending on your method POST/GET, you will see that the browser is actually remembering only the last value recorded by the full-name attribute. Basically if your first input is John Doe (under the attendee fieldset) and your second input is John Green (under the next-of-kin fieldset), the browser will only remember John Green regardless of your method. If you use the GET method only your URL will contain both of the full-name attributes, but not the actual $_GET array itself.
If you want to record both the names you can edit your code to:
<fieldset name="attendee">
<input name="full-name[]">
</fieldset>
<fieldset name="next-of-kin">
<input name="full-name[]">
</fieldset>
By using the [] the browser knows not to remember just the last value of that attribute. Now if you do a var_dump() regardless of your method you should see:
array(1) { ["full-name"]=> array(2) {
[0]=> string(8) "John Doe"
[1]=> string(10) "John Green"
}
}
If by any chance you want to be more specific (since in one of the comments you were mentioning that you are using this in a REST API), you can edit your code like this:
<fieldset name="attendee">
<input name="full-name[attendee]">
</fieldset>
<fieldset name="next-of-kin">
<input name="full-name[next-of-kin]">
</fieldset>
Now if you submit the form, regardless of the method, you will get the following data-structure:
array(1) { ["full-name"]=> array(2) {
["attendee"]=> string(8) "John Doe"
["next-of-kin"]=> string(10) "John Green"
}
}
It is fairly simple from here to call json_encode() on this array and get an actual JSON object(like the one bellow) that you can use with your API:
{"full-name":{"attendee":"John Doe","next-of-kin":"John Green"}}
I would recommend to give every field a different name,
for example if you have two fields, using the GET method, the name/value pairs in the URL will look like this:
index.html?attendee=random&full-name=random2&next-of-kin=random3&full-name=random4
for this code:
<fieldset name="attendee">
<input name="full-name">
</fieldset>
<fieldset name="next-of-kin">
<input name="full-name">
</fieldset>
So which data will be loaded in the backend, if the identifier they are called with are the same but the data different?
if you don't have a backend, and you only use the name field as a selector, I would recommend you to use the class="" field.
If you plan to manipulate these fields using ID selectors (javascript or Jquery) and you would want to keep the functionality separate then I would use unique ids. Specifying an id tag would be better if you plan to select the elements.
<fieldset id="attendeeMain" name="attendee">
<input name="full-name">
</fieldset>
<fieldset id="nextOfKin" name="next-of-kin">
input name="full-name">
</fieldset>

Using checkboxes without a value attribute

I Understand the ins and outs of forms, but say for example I have the following code:
<form method="post" action="urltoserver">
<input type="checkbox" name="mycheckbox" value="1">Question</input>
</form>
Here I have set a value for the $_POST array. However, if I simply want to know if the checkbox is selected or not (ie im not bothered about the returned value), is it feasible/common practice to leave off the value attribute all together? Would it just return true/false in this case?
I'm assuming PHP since you mentioned $_POST; correct me if I'm wrong.
if a checkbox is checked (and there is no value assigned) you should (IIRC) receive an on value back (as unchecked boxes aren't sent with the request). So, if you had:
<form method="POST">
<input type="checkbox" name="foo" /> Foo
<input type="checkbox" name="bar" checked="checked"/> Bar
<input type="checkbox" name="baz" checked="checked"/> Baz
</form>
You'd see:
isset($_POST['foo']) == false
isset($_POST['bar']) == true
isset($_POST['baz']) == true
on the server-side when you went to read the check state.
the easiest thing to do though, if you're learning, is submit it to a page with the following code:
<?php
var_dump($_REQUEST);
That will show you, verbatim, what was submitted (based on the form's populated values). From there you can play with how you want to format the form to receive the values you're expecting.

How to retrieve multiple fields with form in HtmlService?

Here is the situation : I have a form created by HtmlService, and several items have the same names because I want to retrieve them in a array.
Here is an example:
<html>
<form method="post" action="address of my published script (or dev address for the test)" >
<input type="text" name="field" />
<input type="text" name="field" />
<input type="submit" value="Send" />
</form>
</html>
(Ok, it seems useless here, but it'll be interesting when user can add fields of the same name dynamically, so I won't know how many they are).
In the function doPost(e), I wish to have e.parameter.field equals to [value1, value2]. Unfortunately, I only have the first element.
I read that in PHP we can write name="field[]", but it doesn't work either.
Do you know any solution for doing that ?
Thanks for your answers ! :)
e.parameters (note the s at the end) will have precisely what you want.

Question about POST method security

Let say I have a post from like this:
<form action="myApp/form_action.asp" method="post">
First name: <input type="text" name="fname" /><br />
Last name: <input type="text" name="lname" /><br />
<input type="submit" value="Submit" />
</form>
So, let say there is a really bad buy who want to do something in my application. For example, my form_action.asp not only accept param "fname", "lname", but also "gender", can he/she make a request on their own , like this....
<form action="http://www.myDomain.com/myApp/form_action.asp" method="post">
First name: <input type="text" name="fname" /><br />
Last name: <input type="text" name="lname" /><br />
Gender: <input type="text" name="gender" /><br />
<input type="submit" value="Submit" />
</form>
****Updates:****
I don't want the user submit the gender, because I don't want to modify his/her gender after he/she assigned.
If he/she can submit this query, it there any way to avoid him/her to do so? thank you.
You're thinking about this the wrong way. Forget about HTML forms. They're not what your server handles. It handles HTTP requests.
And (pretty obviously) people can send you HTTP requests that contain whatever they want. Not just additional fields, but also fields with values that the form would not allow, or fields with names that are 5000 characters long and/or values that are that long.
So what you absolutely must do is define what constitutes valid input and reject input that isn't. In your case, it's pretty simple: if the form is not supposed to contain a "gender" field, then have the server ignore such a field, or abort with an error if it's present.
Usually you don't have to do anything to ignore fields. But you definitely have to write your app in such a way that it does not accept field values that are not valid.
You cannot avoid this. Inputs coming from the clientside are NEVER secure and can ALWAYS be tampered with.
You'll have to implement your checks serverside, in the ASP file itself.
The reason you can't avoid it is that he doesn't need to make his own copy and submit it from another domain. He can easily modify your site live with javascript (e.g.: firebug) and send the fake request identical to a valid one.
If your form action file i.e. form_action.asp doesn't call for the $_POST['gender'] variable i can't see how it would affect your script.
Make sure that you are sanitizing your variables though, so for first name and last name you would only really want to accept A-Za-z, space and maybe hyphens and apostrophes.
By doing this it doesn't really matter what they send to your form because most of the tags, brackets etc will be removed and any script injected won't run.
Make sure you also escape the variables before you enter them in your database, I use mysql_real_escape_string in php, but don't know any asp so you will have to look it up.