html form: prevent re-submitting while sending - php

I have this form:
<form action="" method="post" name="my_form">
<input type="text" name="my_input">
</form>
You can write some text and the submit by pressing the enter key.
My problem: When you press the enter key multiple times, it'll also sent multiple times to my server.
There are solution like this:
onsubmit="my_button=true;return true;"
But these solutions require a submit button.
Is there a way to do this without adding a (hidden) submit button?

If you want to be absolutely sure, for example, submitting the form twice can cause severe damage/cause malicious things to happen, then you need to check this serverside. One rule of webdevelopment and general development is to never trust your end-user, and by simply blocking the form using JavaScript, you cannot be assured that a malicious user won't be sending the form twice by getting around the JavaScript.
What you can do is something like this:
Important: This is just a proof of concept example to explain the idea, this is not a 100% bulletproof solution.
Form
<?php
session_start();
$_SESSION['nonce'] = random_number();
?>
<html>
...
<form method="post" action="process.php">
<input type="hidden" name="nonce" value="<?php echo $_SESSION['nonce']; ?>" />
... other form elements ...
</form>
...
process.php
<?php
session_start();
$nonce = isset($_POST['nonce']) ? (int)$_POST['nonce'] : 0;
$session_nonce = $_SESSION['nonce'];
if ($_SESSION['nonce'] != $nonce) {
die("Invalid nonce, double submission detected.");
}
$_SESSION['nonce'] += 1; // this will cause the previous check to fail on a second submission.

some like this :
<form onsubmit="send();" method="post" name="my_form">
<input type="submit" name="my_input" id="sub">
</form>
js code:
function send(){
$("#sub").attr('disabled', 'disabled');
$.ajax({
// data
success: function(data){
$("#sub").attr('disabled', false);
}
});
}

Like this (untestet):
var formSubmitted = false;
document.getElementById('my-form').addEventListener('submit', function(){
if(formSubmitted === false) {
formSubmitted = true;
return true;
}
return false;
});

You could disable the button once it's set so the User cannot click it again
<form action="" method="post" name="my_form">
<input type="text" name="my_input" <?php if(isset($_POST['my_input'])) { print
'disabled'; } ?>>
</form>

Related

Redirect to anchor in same page after form submit

I have a website with a landing page, and at the bottom of the page I have a form. All I want to do is show a validation message and redirect the user to the form again so he can look the message without having to scroll.
The code is as follows (it is on the same page):
//validation
if (isset($_POST['submit'])) {
$name = htmlspecialchars(stripslashes(trim($_POST['name'])));
if (!preg_match("/^[A-Za-zÀ-ÖØ-öø-ÿ]/", $name)) {
$name_error = 'invalid name';
}
//i want to redirect as soon as the validation finishes
header('Location: http://localhost/myweb/index.php#contact');
}
<form id="form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<input type="text" name="name" id="name">
<button type="submit" id="submit" name="submit">Send</button>
</form>
I have tried all of the following:
Use of window.location.href = 'index.php#contact'; in the button (onclick) and in the form (onsubmit)
Use of the header in multiple parts of the code, also with exit();
However, and here is the key, I do not want to use another page of php only for validation (since I would need to use session_start() and I want to avoid cookies) AND and I do not want to use an AJAX XMLHttp Request.
Is it possible to do it?
I'm using #contact in form action like this
<form id="form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>#contact" method="POST">
Did you try this?

Two HTML forms submitted by PHP trigger each other

i've got 2 forms on one page, but when I press submit one the other is actioned.
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit" name="getNameSubmit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
if(isset($_REQUEST['fname']) && $_REQUEST['fname']!="")
{
$name = htmlspecialchars($_REQUEST['fname']);
if (empty($name)) {
echo "Hello dear user.";
} else {
echo "Hello $name";
}
}
}
?>
and
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Full text: <input type="text" name="stringtoreplace" value="">
Word(s) to change: <input type="text" name="wordstochange" value="">
Change to: <input type="text" name="wordstoinput" value="">
<input type="submit" name="wordReplaceSubmit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field -- the if(isset) stops a pre-comparison that throws an E_NOTICE level error
if(isset($_REQUEST['stringtoreplace']) && $_REQUEST['stringtoreplace']!="")
{
$stringoutput = htmlspecialchars($_REQUEST['stringtoreplace']);
}
if(isset($_REQUEST['wordstochange']) && $_REQUEST['wordstochange']!="")
{
$tochange = htmlspecialchars($_REQUEST['wordstochange']);
}
if(isset($_REQUEST['wordstoinput']) && $_REQUEST['wordstoinput']!="")
{
$changeto = htmlspecialchars($_REQUEST['wordstoinput']);
}
if (empty($stringoutput)) {
echo "Please enter your text and the words to change.";
} else {
echo str_replace($tochange, $changeto, $stringoutput);
}
}
?>
How can I get one to action without triggering the other? The function and placement isn't a factor here, I'm just doing some practice, but would be nice ton understand why this happens and how to resolve.
<?php echo $_SERVER['PHP_SELF'];?> gives the current URL, so because they're in the same page, it causes the problem. You can check this on inspecting the page Ctrl + Shift + i then clicking on Elements on Chrome.
One solution might be to give different URLs to both the forms or use parameters on post request. Eg.- <?php echo $_SERVER['PHP_SELF'].'?form=form1';?> & <?php echo $_SERVER['PHP_SELF'].'?form=form2';?>
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_GET['form'])){
if($_GET['form'] == 'form1'){
//code for form1
}else{
//code for form2
}
}
}
Ok, let's start on why this is happening.
The action parameter of an HTML tells the browser which URL to send the POST request with the form data. In your case, it's $_SERVER['PHP_SELF'], which is the current PHP script. You use the same for both forms.
When one of the forms is submitted, your PHP script gets called, and all the PHP in the script gets executed. The first part (the one after the first form) checks if ($_SERVER["REQUEST_METHOD"] == "POST"), decides that yes, it was a POST request, and tries to proceed. After that, the second part (the one after the second form), uses the exact same check, decides that yes, it was a POST request, and tries to proceed too.
Ideally, it would be cleaner to have two different pages to process two different forms; but if you prefer to keep all in the same page, you have a couple of different options to distinguish between the two.
1) Use a different query parameter in the action attribute for each form, as suggested by #sauhardnc. The forms would look like:
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>?form=form1">
...
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>?form=form2">
while the PHP side would do something like
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if ($_GET['form'] == 'form1') {
// code for form1
} else {
// code for form2
}
}
2) Use a different input in each form. The forms would look like:
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
...
<input type="hidden" name="form" value="form1">
</form>
...
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
...
<input type="hidden" name="form" value="form2">
</form>
while the PHP side would do something like
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if ($_REQUEST['form'] == 'form1') {
// code for form1
} else {
// code for form2
}
}

Form Submit Button Works, but not Submit() in Link

I've done this so often before on different websites, but can't get it to work now.
I've got a simple form that posts perfectly well using a submit button, but for a specific reason I actually need it to submit via a url link instead. I'm using submit(). The form submits, but the data isn't posting.
What am I missing?
<html>
<body>
<?
if(isset($_POST['bar'])) { echo 'testing button<br>'; }
if(isset($_POST['information'])) {
echo $_POST['information'];
echo '</br>Info successfully posted.';
}
?>
<form action="test.php" method="post" id="fooform">
Hello World.<br>
Select checkbox: <input type="checkbox" id="information" name="information" value="yes">
<input type="submit" name="bar" value="Send"><br>
Confirm and Post<br>
Post Directly
</form>
<script type="text/javascript">
function SubmitForm(formId) {
var oForm = document.getElementById(formId);
alert("Submitting");
if (oForm) { oForm.submit(); }
else { alert("DEBUG - could not find element " + formId); }
}
</script>
</body>
</html>
The form starts to submit, then the href of the link is followed, and this cancels the form submission.
If you are using old-style onclick attributes, then return false; at the end to prevent the default action.
You would, however, be better off using a submit button (you are submitting a form). You can use CSS to change its appearance.
Try this code :
<html>
<body>
<?php
if (isset($_POST['bar'])) {
echo 'testing button<br>';
}
if (isset($_POST['information'])) {
echo $_POST['information'];
echo '</br>Info successfully posted.';
}
?>
<form action="test.php" method="post" id="fooform">
Hello World.<br>
Select checkbox: <input type="checkbox" id="information" name="information" value="yes">
<input type="submit" name="bar" value="Send"><br>
Confirm and Post<br>
Post Directly
</form>
<script type="text/javascript">
function SubmitForm(formId) {
var oForm = document.getElementById(formId);
alert("Submitting");
if (oForm) {
oForm.submit();
}
else {
alert("DEBUG - could not find element " + formId);
}
}
</script>
</body>
</html>
try to submit form with form id in jquery
<a class="submit">Post Directly </a>
$('a.submit').click(function(){
$('#fooform').submit();
})

Add validation to salesforce.com forms

I've been tasked with adding validation to stop spam on a simple contact form. The only problem here is that all the form processing happens on salesforce.com's side. I don't have the file that processes the form so I can't just add simple form validation.
The form's action goes to salesforce as so:
<form action="https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8" method="POST">
I tried doing some javascript validation, but the form still submits no matter what. I have a feeling I need to change the form's action to a new php page I create. I can do the validation there, then if it passes I need to tell it to somehow go to this form action and finish the form processing?
I tried doing the hidden form field idea with jQuery, where you put in a hidden form field that only a bot would somehow fill out. So if that field has a value, then do an alert that it is spam, but this wouldn't work! The form just kept submitting.
Ugh, not sure, please help thanks!
=====EDIT====
What is wrong here?
my button
<input type="button" id="submit" value="Submit">
my jquery
jQuery(document).ready(function() {
jQuery('#submit').click(function() {
var human = $("#human").val();
if(human == 4 ){
$('#form_submit').submit();
}
else {
alert('Please answer the validation question correctly.');
}
});
});
my form action:
<form id="form_submit" action="https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8" method="POST">
and my "human" field:
<input id="human" maxlength="20" name="human" size="30" type="text" />
something like this should work:
Working Example
you want to prevent the default event that happens on form submission.
SO when they click enter, or submit, you want to preventDefault(), then you are free to do what you want. I did ajax as example, because ajax is awesome.
<form id="form_submit" method="POST">
<input type="text" name="email" value="" placeholder="for humans" id="email">
<input type="text" name="robots" value="" placeholder="for robots" id="human">
<input type="submit" value="GO!">
<script>
$("#form_submit").submit(function(e){
// when the form is submitted:
// if the value of #human isn't empty, its a robot
if ($("#human").val() !== "") {
alert('robot!');
return false;
}
// other form validation you may want:
if ($("#email").val() == ""){
alert('missing email');
return false;
}
// STOP THE FORM FROM SUBMITTING ON ITS OWN
e.preventDefault();
// do whatever else you have to do.
$.ajax({
url:"https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8",
data:"field1=value1&field2=value2", // this depends on what your server-side wants
type:"POST",
beforeSend:function(){console.log('sending..');},
error:function(response){console.log('error: ' + response);},
success:function(response){console.log('success!');},
complete:function(){console.log('finished.');}
});
});
</script>
Change your submit button to a normal button. In jQuery add a click method to perform your spam logic. When you really want to submit you can submit the page through jQuery.
Example:
<form id="form_submit" action="https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8" method=" POST">
$("#submit").click(function() {
if(!spam){
$('#form_submit').submit();
}
});

POST without redirect with PHP

I have a simple form for a mailing list that I found at http://www.notonebit.com/projects/mailing-list/
The problem is when I click submit all I want it to do is display a message under the current form saying "Thanks for subscribing" without any redirect. Instead, it directs me to a completely new page.
<form method="POST" action="mlml/process.php">
<input type="text" name="address" id="email" maxlength="30" size="23">
<input type="submit" value="" id="submit"name="submit" >
</form>
You will need AJAX to post the data to your server. The best solution is to implement the regular posting, so that will at least work. Then, you can hook into that using Javascript. That way, posting will work (with a refresh) when someone doesn't have Javascript.
If found a good article on posting forms with AJAX using JQuery .
In addition, you can choose to post the data to the same url. The JQuery library will add the HTTP_X_REQUESTED_WITH header, of which you can check the value in your server side script. That will allow you to post to the same url but return a different value (entire page, or just a specific response, depending on being an AJAX request or not).
So you can actually get the url from your form and won't need to code it in your Javascript too. That allows you to write a more maintanable script, and may even lead to a generic form handling method that you can reuse for all forms you want to post using Ajax.
Quite simple with jQuery:
<form id="mail_subscribe">
<input type="text" name="address" id="email" maxlength="30" size="23">
<input type="hidden" name="action" value="subscribe" />
<input type="submit" value="" id="submit"name="submit" >
</form>
<p style="display: none;" id="notification">Thank You!</p>
<script>
$('#mail_subscribe').submit(function() {
var post_data = $('#mail_subscribe').serialize();
$.post('mlml/process.php', post_data, function(data) {
$('#notification').show();
});
});
</script>
and in your process.php:
<?php
if(isset($_POST['action'])) {
switch($_POST['action']) {
case 'subscribe' :
$email_address = $_POST['address'];
//do some db stuff...
//if you echo out something, it will be available in the data-argument of the
//ajax-post-callback-function and can be displayed on the html-site
break;
}
}
?>
It redirects to a different page because of your action attribute.
Try:
<form method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>">
<input type="text" name="address" id="email" maxlength="30" size="23" />
<input type="submit" value="" id="submit" name="submit" />
</form>
<?php if (isset($_POST['submit'])) : ?>
<p>Thank you for subscribing!</p>
<?php endif; ?>
The page will show your "Thank You" message after the user clicks your submit button.
Also, since I don't know the name of the page your code is on, I inserted a superglobal variable that will insert the the filename of the currently executing script, relative to the document root. So, this page will submit to itself.
You have to use AJAX. But that requires JavaScript to be active at the users Brwoser.
In my opinion it's the only way to do without redirect.
to send a form request without redirecting is impossible in php but there is a way you can work around it.
<form method="post" action="http://yoururl.com/recv.php" target="_self">
<input type="text" name="somedata" id="somedata" />
<input type="submit" name="submit" value="Submit!" />
</form>
then for the php page its sending to have it do something but DO NOT echo back a result, instead simply redirect using
header( 'Location: http://yourotherurl.com/formpage' );
if you want it to send back a success message simply do
$success = "true";
header( 'Location: http://yourotherurl.com/formpage?success='.$success);
and on the formpage add
$success = $_GET['success'];
if($success == "true"){ echo 'Your success message'; } else { echo
'Your failure message';
Return and print the contents of another page on the current page.
index.php
<html>
<body>
<p>index.php</p>
<form name="form1" method="post" action="">
Name: <input type="text" name="search">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$_POST['search'];
include 'test.php';
}
?>
</body>
</html>
test.php
<?php
echo 'test.php <br/>';
echo 'data posted is: ' . $_POST['search'];
?>
Result:
Just an idea that might work for you assuming you have no control over the page you are posting to:
Create your own "proxy php target" for action and then reply with the message you want. The data that was posted to your php file can then be forwarded with http_post_data (Perform POST request with pre-encoded data). You might need to parse it a bit.
ENGLISH Version
It seems that no one has solved this problem without javascript or ajax
You can also do the following.
Save a php file with the functions and then send them to the index of your page
Example
INDEX.PHP
<div>
<?php include 'tools/edit.php';?>
<form method="post">
<input type="submit" name="disable" value="Disable" />
<input type="submit" name="enable" value="Enable" />
</form>
</div>
Tools.php (It can be any name, note that it is kept in a folder lame tools)
<?php
if(isset($_POST['enable'])) {
echo "Enable";
} else {
}
if(isset($_POST['disable'])) {
echo "Disable";
} else {
}
?>
Use
form onsubmit="takeActions();return false;"
function takeAction(){
var value1 = document.getElementById('name').innerHTML;
// make an AJAX call and send all the values to it
// Once , you are done with AJAX, time to say Thanks :)
document.getElementById('reqDiv').innerHTML = "Thank You for subscribing";
}

Categories