Form Double Post Issue - html

I understand that double posts has been a problem with forms forever.
I am using the token server-side method to handle this issue, but I find that it doesn't seem to work flawlessly. I have the system set to create a unique token for every form, and then record that token in a SESSION after it has been posted.
The SESSION is actually an array of every form the user has ever posted (to be reset when the SESSION expires), and on each submit the system checks in_array() to see if that form has ever already been posted... if so then it stops them.
Seems like in production the system cannot record the completed token into the SESSION quick enough to deal with double clicks on the submit button. So revisiting an old page is handled fine, but the immediate double click of the submit creates a problem.
Not sure what I can do to fix this issue.

How about disabling the submit button immediately upon clicking (via Javascript, with an onClick handler)? This obviously won't fix all issues, but it might cover the cases where the system isn't quick enough to record the token into SESSION.

I have had this issue as well with something internal for the company I am working for. In my experience people click multiple times because they don't think anything is happening. What I have done is to remove the ability to submit the form and display some sort of message saying that the information is being processed.
Pop-up divs and just disabling the button work well.

I had same problem and I resolve with jQuery.
I added class singleClick in submit button there I would like to have single click and also added some javascript code
<input type="submit" class="singleClick" value="Send Request">
$(function () {
$('.singleClick').on('click', function () {
$(this).attr('disabled', true);
});
});

Related

Mozilla Firefox form values reset on history.back

I'm writing a PHP script. I've got a form uses post method and action to another page. If an error occurs, I show a message on that target page, and let the user go back via a link that triggers history.back(); javascript function.
So user clicks that link and turns back to the page includes form and values entered by user should remain in inputs.
They stay on Chrome, but lost in Firefox. Is there a way to keep DOM information on all major browsers using history, or is the only way to do that is to use a cache like session, cookies, etc. ?
You could, and I know it's annoying, capture your POST data and turn it into SESSION variables, then repopulate input fields on browser back.
Alternatively, You can submit the form to an iframe and process, or use ajax to process and depending on the result, trigger a new page load or not.

Clear all fields in a form upon going back with browser back button

I need a way to clear all the fields within a form when a user uses the browser back button. Right now, the browser remembers all the last values and displays them when you go back.
More clarification on why I need this
I've a disabled input field whose value is auto-generated using an algorithm to make it unique within a certain group of data. Once I've submitted the form and data is entered into the database, user should not be able to use the same value again to submit the same form. Hence I've disabled the input field in the first place. But if the user uses the browser back button, the browser remembers the last value and the same value is retained in the input field. Hence the user can submit the form with the same value again.
What I don't understand is what exactly happens when you press the browser back button. It seem like the entire page is retrieved from cache without ever contacting the server if the page size is within the browser cache limit. How do I ensure that the page is loaded from the server regardless of browser setting when you press the browser back button?
Another way without JavaScript is to use <form autocomplete="off"> to prevent the browser from re-filling the form with the last values.
See also this question
Tested this only with a single <input type="text"> inside the form, but works fine in current Chrome and Firefox, unfortunately not in IE10.
Modern browsers implement something known as back-forward cache (BFCache). When you hit back/forward button the actual page is not reloaded (and the scripts are never re-run).
If you have to do something in case of user hitting back/forward keys - listen for BFCache pageshow and pagehide events:
window.addEventListener("pageshow", () => {
// update hidden input field
});
See more details for Gecko and WebKit implementations.
I came across this post while searching for a way to clear the entire form related to the BFCache (back/forward button cache) in Chrome.
In addition to what Sim supplied, my use case required that the details needed to be combined with Clear Form on Back Button?.
I found that the best way to do this is in allow the form to behave as it expects, and to trigger an event:
$(window).bind("pageshow", function() {
var form = $('form');
// let the browser natively reset defaults
form[0].reset();
});
If you are not handling the input events to generate an object in JavaScript, or something else for that matter, then you are done. However, if you are listening to the events, then at least in Chrome you need to trigger a change event yourself (or whatever event you care to handle, including a custom one):
form.find(':input').not(':button,:submit,:reset,:hidden').trigger('change');
That must be added after the reset to do any good.
If you need to compatible with older browsers as well "pageshow" option might not work. Following code worked for me.
$(window).load(function() {
$('form').get(0).reset(); //clear form data on page load
});
This is what worked for me.
$(window).bind("pageshow", function() {
$("#id").val('');
$("#another_id").val('');
});
I initially had this in the $(document).ready section of my jquery, which also worked. However, I heard that not all browsers fire $(document).ready on hitting back button, so I took it out. I don't know the pros and cons of this approach, but I have tested on multiple browsers and on multiple devices, and no issues with this solution were found.
Because I have some complicated forms with some fields that are pre-fill by JS, clearing all fields is not suitable for me. So I found this solution, it detects the page was accessed by hitting the back/forward button and then does a page reload to get everything back to its original state. I think it will be useful to someone:
window.onpageshow = function(event) {
if (event.persisted || performance.getEntriesByType("navigation")[0].type === 'back_forward') {
location.reload();
}
};
As indicated in other answers setting autocomplete to "off" does the trick, but in php, what worked for me looks like this...
$form['select_state'] = array(
'#type' => 'select',
'#attributes' => array('autocomplete' =>'off'),
'#options' => $options_state,
'#default_value' => 'none');

How can you check to see if someone has modified your HTML (using something like Firebug)?

Is there an easy way to check to see if someone has modified your HTML? I am currently writing some code that takes data from the DOM and submits it to the backend where it will of course be sanitized and checked for accuracy, but I was wondering if there was a way to kind of head that off at the pass.
For instance, if I have a hidden input with a number in it and someone modifies that number in Firebug before submitting it to my server, is there a way to check to see if the actual HTML was modified before submitting the request to the server and basically telling them HEY BUDDY STOP MESSING WITH MY STUFF.
I'm not entirely sure this is possible, but if it is, I do not know how to do it.
Hmm, I'd say that the HTML on your users' browser is actually theirs. (i.e. nothing wrong with greasemonkey) Stuff isn't yours again until it arrives at your server in the form of the URL, HTML form input parameters, and cookies -- all of which can of course be modified unbenknownst to you. So you should continue to validate such data; there's no magic bullet to allow for a trusted client experience.
You could send along with your hidden value another value that is the result of a complex computation you performed involving the hidden value and some secret value that never gets sent to the client. Then when you receive the hidden value simply perform another calculation that reverses the first one. If you don't get your secret value back then you know they have changed the hidden value.
Of course, this is still not going to be that secure as someone can easily do some experiments on your site and find out what that secret value is based solely off of your hidden value and verification value and then change the verification value as well.
It is possible to come up with a computation that will make it rather difficult (but not impossible) to crack this type of verification. However, with the time and effort that would be involved in coming up with such a computation and then staying on top of it to ensure no new exploits come out for it, you would probably be better off just sanitizing the data as you receive it.
In my opinion you are better off not relying on any data received by the user. There are certainly tricks that can be done to do what you ask and this may be one of them but most all of these tricks are ones that can most likely be figured out by an attacker given enough time.
You could see if somebody is changing hidden input elements with Firebug using JavaScript, but the idea sounds silly.
All your critical validation should be done server-side.
You can't rely on anything the client sends being accurate. If somebody really wanted to "mess with your stuff", they could easily (for example) write a Python script to submit data to your server.
Here's a jQuery-based sample of what I was alluding to in my comment:
Live Demo #2
Click Submit: the background will turn green - nothing was changed.
Change the value of a hidden input, click Submit: the background will turn red - something was changed.
HTML:
<form id="myForm" method="post" action="">
<input type="hidden" value="123" />
<input type="hidden" value="456" />
<input type="submit" />
</form>
JS #2:
$('#myForm input[type="hidden"]').each(function() {
$(this).data('originalValue', $(this).val());
});
$('#myForm').submit(function(){
$(this).find('input[type="hidden"]').each(function() {
if ($(this).val() != $(this).data('originalValue')) {
$('body').css('background', 'red');
return false;
}
//just for testing:
$('body').css('background', 'green');
});
return false;
});
There are things you can do in JavaScript, like keeping a copy of the expected value buried in JavaScript:
var originalHiddenFieldValue = document.getElementById("myHiddenField").value;
... later...
if (originalHiddenFieldValue !== document.getElementById("myHiddenField").value)
alert("Hey, stop it!");
At the end of the day though, all the user would have to do is detach any event handlers on your submit button to override any validation and your code would be useless. If they're smart enough to be overriding values using Firebug, you can make a good bet that they'd be willing to go a bit further to modify your scripts too.
If you're trying to check for these things, the only way you can do it with 100% confidence is to check the hidden field server-side, and compare the values, as you have said you are doing anyway.

How to prevent robots from automatically filling up a form?

I'm trying to come up with a good enough anti-spamming mechanism to prevent automatically generated input. I've read that techniques like captcha, 1+1=? stuff work well, but they also present an extra step impeding the free quick use of the application (I'm not looking for anything like that please).
I've tried setting some hidden fields in all of my forms, with display: none;
However, I'm certain a script can be configured to trace that form field id and simply not fill it.
Do you implement/know of a good anti automatic-form-filling-robots method? Is there something that can be done seamlessly with HTML AND/OR server side processing, and be (almost) bulletproof? (without JS as one could simply disable it).
I'm trying not to rely on sessions for this (i.e. counting how many times a button is clicked to prevent overloads).
I actually find that a simple Honey Pot field works well. Most bots fill in every form field they see, hoping to get around required field validators.
http://haacked.com/archive/2007/09/11/honeypot-captcha.aspx
If you create a text box, hide it in javascript, then verify that the value is blank on the server, this weeds out 99% of robots out there, and doesn't cause 99% of your users any frustration at all. The remaining 1% that have javascript disabled will still see the text box, but you can add a message like "Leave this field blank" for those such cases (if you care about them at all).
(Also, noting that if you do style="display:none" on the field, then it's way too easy for a robot to just see that and discard the field, which is why I prefer the javascript approach).
An easy-to-implement but not fool-proof (especially on "specific" attacks) way of solving anti-spam is tracking the time between form-submit and page-load.
Bots request a page, parse the page and submit the form. This is fast.
Humans type in a URL, load the page, wait before the page is fully loaded, scroll down, read content, decide wether to comment/fill in the form, require time to fill in the form, and submit.
The difference in time can be subtle; and how to track this time without cookies requires some way of server-side database. This may be an impact in performance.
Also you need to tweak the threshold-time.
What if - the Bot does not find any form at all?
3 examples:
Insert your form using AJAX
If you are OK with users having JS disabled and not being able to see/ submit a form, you can notify them and have them enable Javascript first using a noscript statement:
<noscript>
<p class="error">
ERROR: The form could not be loaded. Please enable JavaScript in your browser to fully enjoy our services.
</p>
</noscript>
Create a form.html and place your form inside a <div id="formContainer"> element.
Inside the page where you need to call that form use an empty <div id="dynamicForm"></div> and this jQuery: $("#dynamicForm").load("form.html #formContainer");
Build your form entirely using JS
// THE FORM
var $form = $("<form/>", {
appendTo : $("#formContainer"),
class : "myForm",
submit : AJAXSubmitForm
});
// EMAIL INPUT
$("<input/>",{
name : "Email", // Needed for serialization
placeholder : "Your Email",
appendTo : $form,
on : { // Yes, the jQuery's on() Method
input : function() {
console.log( this.value );
}
}
});
// MESSAGE TEXTAREA
$("<textarea/>",{
name : "Message", // Needed for serialization
placeholder : "Your message",
appendTo : $form
});
// SUBMIT BUTTON
$("<input/>",{
type : "submit",
value : "Send",
name : "submit",
appendTo : $form
});
function AJAXSubmitForm(event) {
event.preventDefault(); // Prevent Default Form Submission
// do AJAX instead:
var serializedData = $(this).serialize();
alert( serializedData );
$.ajax({
url: '/mail.php',
type: "POST",
data: serializedData,
success: function (data) {
// log the data sent back from PHP
console.log( data );
}
});
}
.myForm input,
.myForm textarea{
font: 14px/1 sans-serif;
box-sizing: border-box;
display:block;
width:100%;
padding: 8px;
margin-bottom:12px;
}
.myForm textarea{
resize: vertical;
min-height: 120px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="formContainer"></div>
Bot-bait input
Bots like (really like) saucy input elements like:
<input
type="text"
name="email"
id="email"
placeholder="Your email"
autocomplete="nope"
tabindex="-1"
They wll be happy to enter some value such as
`dsaZusil#kddGDHsj.com`
After using the above HTML you can also use CSS to not display the input:
input[name=email]{ /* bait input */
/* do not use display:none or visibility:hidden
that will not fool the bot*/
position:absolute;
left:-2000px;
}
Now that your input is not visible to the user expect in PHP that your $_POST["email"] should be empty (without any value)! Otherwise don't submit the form.
Finally,all you need to do is create another input like
<input name="sender" type="text" placeholder="Your email"> after (!) the "bot-bait" input for the actual user Email address.
Acknowledgments:
Developer.Mozilla - Turning off form autocompletition
StackOverflow - Ignore Tabindex
What I did is to use a hidden field and put the timestamp on it and then compared it to the timestamp on the Server using PHP.
If it was faster than 15 seconds (depends on how big or small is your forms) that was a bot.
Hope this help
A very effective way to virtually eliminate spam is to have a text field that has text in it such as "Remove this text in order to submit the form!" and that text must be removed in order to submit the form.
Upon form validation, if the text field contains the original text, or any random text for that matter, do not submit the form. Bots can read form names and automatically fill in Name and Email fields but do not know if they have to actually remove text from a certain field in order to submit.
I implemented this method on our corporate website and it totally eliminated the spam we were getting on a daily basis. It really works!
How about creating a text field input box the same color as the background which must remain blank. This will get around the problem of a bot reading display:none
http://recaptcha.net/
reCAPTCHA is a free antibot service that helps digitize books
It has been aquired by Google (in 2009):
https://www.google.com/recaptcha
https://developers.google.com/recaptcha/
Also see
https://en.wikipedia.org/wiki/ReCAPTCHA
https://en.wikipedia.org/wiki/CAPTCHA for more general information
Many of those spam-bots are just server-side scripts that prowl the web. You can combat many of them by using some javascript to manipulate the form request before its sent (ie, setting an additional field based on some client variable). This isn't a full solution, and can lead to many problems (eg, users w/o javascript, on mobile devices, etc), but it can be part of your attack plan.
Here is a trivial example...
<script>
function checkForm()
{
// When a user submits the form, the secretField's value is changed
$('input[name=secretField]').val('goodValueEqualsGoodClient');
return true;
}
</script>
<form id="cheese" onsubmit="checkForm">
<input type="text" name="burger">
<!-- Check that this value isn't the default value in your php script -->
<input type="hidden" name="secretField" value="badValueEqualsBadClient">
<input type="submit">
</form>
Somewhere in your php script...
<?php
if ($_REQUEST['secretField'] != 'goodValueEqualsGoodClient')
{
die('you are a bad client, go away pls.');
}
?>
Also, captchas are great, and really the best defense against spam.
I'm surprised no one had mentioned this method yet:
On your page, include a small, hidden image.
Place a cookie when serving this image.
When processing the form submission, check for the cookie.
Pros:
convenient for user and developer
seems to be reliable
no JavaScript
Cons:
adds one HTTP request
requires cookies to be enabled on the client
For instance, this method is used by the WordPress plugin Cookies for Comments.
With the emergence of headless browsers (like phantomjs) which can emulate anything, you can't suppose that :
spam bots do not use javascript,
you can track mouse events to detect bot,
they won't see that a field is visually hidden,
they won't wait a given time before submitting.
If that used to be true, it is no longer true.
If you wan't an user friendly solution, just give them a beautiful "i am a spammer" submit button:
<input type="submit" name="ignore" value="I am a spammer!" />
<input type="image" name="accept" value="submit.png" alt="I am not a spammer" />
Of course you can play with two image input[type=image] buttons, changing the order after each load, the text alternatives, the content of the images (and their size) or the name of the buttons; which will require some server work.
<input type="image" name="random125454548" value="random125454548.png"
alt="I perfectly understand that clicking on this link will send the
e-mail to the expected person" />
<input type="image" name="random125452548" value="random125452548.png"
alt="I really want to cancel the submission of this form" />
For accessibility reasons, you have to put a correct textual alternative, but I think that a long sentence is better for screenreaders users than being considered as a bot.
Additional note: those examples illustrate that understanding english (or any language), and having to make a simple choice, is harder for a spambot than : waiting 10 seconds, handling CSS or javascript, knowing that a field is hidden, emulating mouse move or emulating keyboard typing, ...
A very simple way is to provide some fields like <textarea style="display:none;" name="input"></textarea> and discard all replies that have this filled in.
Another approach is to generate the whole form (or just the field names) using Javascript; few bots can run it.
Anyway, you won't do much against live "bots" from Taiwan or India, that are paid $0.03 per one posted link, and make their living that way.
I have a simple approach to stopping spammers which is 100% effective, at least in my experience, and avoids the use of reCAPTCHA and similar approaches. I went from close to 100 spams per day on one of my sites' html forms to zero for the last 5 years once I implemented this approach.
It works by taking advantage of the e-mail ALIAS capabilities of most html form handling scripts (I use FormMail.pl), along with a graphic submission "code", which is easily created in the most simple of graphics programs. One such graphic includes the code M19P17nH and the prompt "Please enter the code at left".
This particular example uses a random sequence of letters and numbers, but I tend to use non-English versions of words familiar to my visitors (e.g. "pnofrtay"). Note that the prompt for the form field is built into the graphic, rather than appearing on the form. Thus, to a robot, that form field presents no clue as to its purpose.
The only real trick here is to make sure that your form html assigns this code to the "recipient" variable. Then, in your mail program, make sure that each such code you use is set as an e-mail alias, which points to whatever e-mail addresses you want to use. Since there is no prompt of any kind on the form for a robot to read and no e-mail addresses, it has no idea what to put in the blank form field. If it puts nothing in the form field or anything except acceptable codes, the form submission fails with a "bad recipient" error. You can use a different graphic on different forms, although it isn't really necessary in my experience.
Of course, a human being can solve this problem in a flash, without all the problems associated with reCAPTCHA and similar, more elegant, schemes. If a human spammer does respond to the recipient failure and programs the image code into the robot, you can change it easily, once you realize that the robot has been hard-coded to respond. In five years of using this approach, I've never had a spam from any of the forms on which I use it nor have I ever had a complaint from any human user of the forms. I'm certain that this could be beaten with OCR capability in the robot, but I've never had it happen on any of my sites which use html forms. I have also used "spam traps" (hidden "come hither" html code which points to my anti-spam policies) to good effect, but they were only about 90% effective.
Another option instead of doing random letters and numbers like many websites do, is to do random pictures of recognizable objects. Then ask the user to type in either what color something in the picture is, or what the object itself is.
All in all, every solution is going to have its advantages and disadvantages. You are going to have to find a happy median between too hard for users to pass the antispam mechanism and the number of spam bots that can get through.
the easy way i found to do this is to put a field with a value and ask the user to remove the text in this field. since bots only fill them up. if the field is not empty it means that the user is not human and it wont be posted. its the same purpose of a captcha code.
I'm thinking of many things here:
using JS (although you don't want it) to track mouse move, key press, mouse click
getting the referral url (which in this case should be one from the same domain) ... the normal user must navigate through the website before reaching the contact form: PHP: How to get referrer URL?
using a $_SESSION variable to acquire the IP and check the form submit against that list of IPs
Fill in one text field with some dummy text that you can check on server side if it had been overwritten
Check the browser version: http://chrisschuld.com/projects/browser-php-detecting-a-users-browser-from-php.html ... It's clear that a bot won't use a browser but just a script.
Use AJAX to send the fields one by one and check the difference in time between submissions
Use a fake page before/after the form, just to send another input
I've added a time check to my forms. The forms will not be submitted if filled in less than 3 seconds and this was working great for me especially for the long forms. Here's the form check function that I call on the submit button
function formCheck(){
var timeStart;
var timediff;
$("input").bind('click keyup', function () {
timeStart = new Date().getTime();
});
timediff= Math.round((new Date().getTime() - timeStart)/1000);
if(timediff < 3) {
//throw a warning or don't submit the form
}
else submit(); // some submit function
}
Decided to add another answer, sorry.
We use a combination of two:
Honeypot field with name="email" (already mentioned by other answers) just be sure to use a sophisticated way to hide it , like moving off the screen or something. Because bots can detect display:none
A hidden field that is set by JavaScript when the user clicks (or focuses if you want to be TAB-friendly) on a required field (wasn't mentioned in other answers)
The 2nd option can even protect from a headless-browser type of spam (using phatnom.js or Selenium) because even JavaScript-bots don't bother actually clicking textboxes.
Blocks 99% of bots.
PS. Make sure to use the focus trick only on fields that are not being filled by password managers like LastPass or 1Passwor.
For the same reasons - mark your honeypot with autocomplete="false" tabindex="-1"
The best solution I've found to avoid getting spammed by bots is using a very trivial question or field on your form.
Try adding a field like these :
Copy "hello" in the box aside
1+1 = ?
Copy the website name in the box
These tricks require the user to understant what must be input on the form, thus making it much harder to be the target of massive bot form-filling.
EDIT
The backside of this method, as you stated in your question, is the extra step for the user to validate its form.
But, in my opinion, it is far simpler than a captcha and the overhead when filling the form is not more than 5 seconds, which seems acceptable from the user point of view.
Its just an idea, id used that in my application and works well
you can create a cookie on mouse movement with javascript or jquery and in server side check if cookie exist, because only humans have mouse, cookie can be created only by them
the cookie can be a timestamp or a token that can be validate
In my experience, if the form is just a "contact" form you don't need special measures. Spam get decently filtered by webmail services (you can track webform requests via server-scripts to see what effectively reach your email, of course I assume you have a good webmail service :D)
Btw I'm trying not to rely on sessions for this (like, counting how
many times a button is clicked to prevent overloads).
I don't think that's good, Indeed what I want to achieve is receiving emails from users that do some particular action because those are the users I'm interested in (for example users that looked at "CV" page and used the proper contact form). So if the user do something I want, I start tracking its session and set a cookie (I always set session cookie, but when I don't start a session it is just a fake cookie made to believe the user has a session). If the user do something unwanted I don't bother keeping a session for him so no overload etc.
Also It would be nice for me that advertising services offer some kind of api(maybe that already exists) to see if the user "looked at the ad", it is likely that users looking at ads are real users, but if they are not real well at least you get 1 view anyway so nothing loss. (and trust me, ads controls are more sophisticated than anything you can do alone)
Actually the trap with display: none works like a charm. It helps to move the CSS declaration to a file containing any global style sheets, which would force spam bots to load those as well (a direct style="display:none;" declaration could likely be interpreted by a spam bot, as could a local style declaration within the document itself).
This combined with other countermeasures should make it moot for any spam bots to unload their junk (I have a guest book secured with a variety of measures, and so far they have fallen for my primary traps - however, should any bot bypass those, there are others ready to trigger).
What I'm using is a combination of fake form fields (also described as invalid fields in case a browser is used that doesn't handle CSS in general or display: none in particular), sanity checks (i. e. is the format of the input valid?), time stamping (both too fast and too slow submissions), MySQL (for implementing blacklists based on e-mail and IP addresses as well as flood filters), DNSBLs (e. g. the SBL+XBL from Spamhaus), text analysis (e. g. words that are a strong indication for spam) and verification e-mails (to determine whether or not the e-mail address provided is valid).
One note on verification mails: This step is entirely optional, but when one chooses to implement it, this process must be as easy-to-use as possible (that is, it should boil down to clicking a link contained in the e-mail) and cause the e-mail address in question to be whitelisted for a certain period of time so that subsequent verifications are avoided in case that user wants to make additional posts.
I use a method where there is a hidden textbox. Since bots parse the website they probably fill it. Then I check it if it is empty if it is not website returns back.
Add email verification. The user receives an email and he needs to click a link. Otherwise discard the post in some time.
You can try to cheat spam-robots by adding the correct action atribute after Javascript validation.
If the robot blocks Javascript they can never submit the form correctly.
HTML
<form id="form01" action="false-action.php">
//your inputs
<button>SUBMIT</button>
</form>
JAVASCRIPT
$('#form01 button').click(function(){
//your Validations and if everything is ok:
$('#form01').attr('action', 'correct-action.php').on("load",function(){
document.getElementById('form01').submit()
});
})
I then add a "callback" after .attr() to prevent errors.

Do all browser's treat enter (key 13) the same inside form?

I have a form with multiple submit buttons, each of which is relevant to how the user wants the data saved and/or loaded.
The problem is (or was) that if a user pressed enter on the last (or any other) input within the form, the submit button that seemed to be called was the "load saved formed" which is at the top of the form. All attempts to user javascript to have the return button default to the "save form" seemed useless, almost as if the browser was too busy already submitting the form to have any js interfere.
Finally, in FireFox 3.5, I actually had the server-side script echo out what it received for the post variable and discovered that none of the submit button values were being passed back to the server. As it turns out, I have hooks in the script for when the user hits "Save" or "Save and Print", etc, but if the user uses the "load page" it simply updates a variable and continues loading the page normally with that variable in context.
So with no submit button value at all, it did the same thing, it simply loaded the page.
So, on to the big question:
Is this typical browser behavior? Maybe even reliable browser behavior? Will hitting enter always submit the form as though no submit button was pressed at all, or do some browsers like to pick a button to use as the default when the user presses enter?
If it is typical behavior, what is the suggested course of action? I was going to have the script save anything no matter what, so long as there was data in the form, but then I realized that this was even more dangerous, because if the user loads one saved form, changes there mind, and changes the form dates and hits "Load Form", then it will save the form data from the pervious form for the new dates they have requested.
I considered setting it up so that changing the load form inputs (selects with dates and other particulars) would clear the form so that the server still recieved an empty form and thus would not overwrite any previous data, but this is risky as well, as many users will certainly notice and think that their data has been lost, etc, and there is always the slight chance that the user will be almost done with the form, go up to the top and fiddle with the form-load selects just to confirm they chose the right what nots and then be forced to start from scratch.
I should just have two forms, one for loading, one for the data, but the problem with that is that all of the data in the load part of the form does get used by the main form. I could write more js to combine the two on submit, or hide the data in the second form, but all of that seems clunky.
Essentially, I need a setup such that the top part of the form is independent of the main form, but not vice versa. Submitting the upper form does not submit the lower, but submitting the lower does submit the higher.
Okay,I've gone on long enough. Basically I'm wondering if a solution already exists or if anyone else has run into this and found a clever fix. I thought simply having the form save whenever the form wasn't empty was pretty clever, until it occurred to me that when the user goes to the page, it auto-loads the most applicable form given the date, and thus changing the load variables will almost always caused trouble.
Having read the possible duplicate that Artelius was good enough to draw my attention to, I'm still unclear on the consistency across browsers regarding the Enter button as submit.
It seems that almost everyone in that question assumed that hitting enter presses the first available submit, which was also my assumption until a friend suggested I hide (via CSS) another submit button at the top of the form with whatever I wanted enter to achieve. It was when this got me the same results that I finally viewed what was being passed to the server (ie nothing in terms of a submit value). So that means either
a) the "enter as no submit button just submit" is new behavior for some or all browsers,
b) the "enter as just submit" vs "enter as first submit button" is just browser choice, no trends, just typical cross-browser unreliability, or
c) Everyone just keeps assuming that the "enter as first submit button" is the case because most of us only code if (situation1) else (assume not situation1) and none of us are really sure what the browser is doing.
I highly doubt it's that last one, but then again, I also highly doubt most of us know which browsers do which. I'd sure like it if there was a straight answer I could pass along.
Oh, and finally: While I know it would be far simpler to use buttons, and I am taking that under serious consideration, I would also like to consider other options, since really the only need for less submit buttons I have is for when users hit enter instead of one of the buttons.
Actually, let me get carried away one more second:
The only thing I really need to know is whether or not they hit enter FROM one of the text inputs. If I could pass that along to the server, I'd know if I should save or reload the form. But the problem is (or at least what I've had troubles with) is that when the user hits enter in an input, it seems like there isn't any more playtime with js to capture anything, and in some cases, it seems like the browser is triggering the onclick for whichever submit button and thus not really allowing me to know the real event that triggered that. I'll play around more with jquery, but has this behavior been observeed by anyone else?
My best advise would be to only have on submit button, and let that submit what ever is the most common usage of the form. Let the rest of the buttons just be normal buttons, which you can hook click events onto.
Just make sure you make it very clear which button will be "pressed" when the user hits enter. Let the submit button be the biggest one. If you have 3 buttons that are used equally as much, I would just drop having a submit button at all...
edit: I'm pretty sure most browsers will post all the data inside a form. If you want to do some checking on the data before posting you could add a listener for onsubmit
<form onsubmit="checkData(this);" ... >
Passing in this will let you check which form is actually being submitted:
function checkData(form) {
var formName = form.id;
//check all the data based on which form is being submitted
}
The HTML5 spec specifies synthetic click activation steps for implicit form submission:
A form element’s default button is the first Submit Button in tree order whose form owner is that form element.
If the user agent supports letting the user submit a form implicitly (for example, on some platforms hitting the "enter" key while a text field is focused implicitly submits the form), then doing so for a form whose default button has a defined activation behavior must cause the user agent to run synthetic click activation steps on that default button.