Add validation to salesforce.com forms - php

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();
}
});

Related

html form: prevent re-submitting while sending

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>

jQuery input value not updating with form submission

Before my HTML form submission, I am putting some values in my hidden input element, which is not submitted with my form, any error or something?
For ex:
Below is my form function:
<form id="clientForm" name="clientForm" method="post" enctype="multipart/form-data" action="clients.php" onClick="beforeSubmit(); return false;">
<input type="text" name="OLD_BRANCH_FILTERS_ALL" id="OLD_BRANCH_FILTERS_ALL" value="">
</form>
Below is my JS function:
<script language="javascript" type="text/javascript">
function beforeSubmit(){
$('#OLD_BRANCH_FILTERS_ALL').attr('value', 'xyz');
alert(document.getElementById('OLD_BRANCH_FILTERS_ALL').value);
document.clientForm.action = 'clients.php?saveBtn=Save';
document.clientForm.submit();
}
</script>
Now, When I check the form request $_REQUEST in PHP, it shows no value in element.
Any clue why its not working.
Thanks in advance !
your onlick is not called in time to set the values, try it this way
<form id="clientForm" name="clientForm" method="post" enctype="multipart/form-data" action="clients.php">
<input type="text" name="OLD_BRANCH_FILTERS_ALL" id="OLD_BRANCH_FILTERS_ALL" value="">
</form>
and the jquery
$('#clientform').submit(function() {
beforeSubmit();
});
Also, if you also wanted to provide validation to the field you could use,
$('#clientform').submit(function(e) {
beforeSubmit();
if (!{VALID}) {
e.preventDefault();
}
});

form submits before validation in php

I have a form which I want to submit, so when I click on submit it goes to the selectorpage.php and finds the selected function type e.g. login in this, which further calls the controller to execute the function. Issue I have is that there is a function called validateForm() in js, as soon as I click the submit button, it goes to the selectorPage.php. I wanted to stop the form submission, perform validation through js and then submit the form from there, I used onsubmit = return false; in form tag but it just blocks the form of doing anything further. And I also don't know how to redirect the form to the selectorPage if it somehow works in js. So anybody would like to give me an idea how to submit form from js and then redirect that page to selectorPage.php. Thanks
<form method="post" action="selector.php?type=login" id="login" id="loginForm">
<div class="row">
<div class="offset1 span1">
<div class="lbel">
<label class="control-label" for "loginName">
Username/Email
</label>
</div>
<div class="lbl_inpuCnt">
<input type="text" class="input-xlarge" id="loginName"
name="loginName" maxlength="50"/>
</div>
<div id="usernameError"> </div>
<div class="lbel">
<label class="control-label" for="loginPassword">
Password
</label>
</div>
<div class="controls">
<input type="password" class="input-xlarge"
id="loginPassword" name="loginPassword"
maxlength="50"/>
</div>
<div id="passwordError"> </div><br/>
</div>
</div>
<div style="margin-left: 55px;">
<input class="btn" style="width: 80px;" type="reset"
name="reset" value="Reset"/>
<input class="btn" style="width: 80px;" type="submit"
name="submit" value="Login" onclick="validateForm();"/>
</div>
</form>
this is the javascript according to the code above
function validateForm(){
form = document.forms['loginForm'];
if(document.getElementById('loginName').value == "")
document.getElementById('usernameError').innerHTML = 'Invalid username or email';
else{
document.getElementById('usernameError').innerHTML = "&nbsp";
form.submit();
}
} //suppose it for the email validation only for the time being
you could try
<form ... onsubmit="return validateForm();"
in the validateForm() function use
return true / false
depending if errors are found.
Here is the canonical way using inline event handling - see further down how it could be made unobtrusive. Also only have ONE id on the form tag, also NEVER call anything submit in a form it is a reserved word and will block submitting by script (which is what you tried to do)
<form id="loginform" ... onsubmit="return validate(this)">
<div style="margin-left: 55px;">
<input class="btn" style="width: 80px;" type="reset" name="reset" value="Reset" onclick="clearFields()"/>
<input class="btn" style="width: 80px;" type="submit" value="Login" />
</div>
</form>
this is the javascript
function validateForm(form){ // passing form object
document.getElementById('usernameError').innerHTML = ""; // reset
if (form.loginName.value == "") {
document.getElementById('usernameError').innerHTML = "Invalid username";
return false;
}
return true;// allow submission
}
Alternative
<form id="loginform" ..... No event handler here ...>
Script:
window.onload=function() {
document.getElementById("loginform").onsubmit=function() {
document.getElementById('usernameError').innerHTML = ""; // reset
if (this.loginName.value == "") { // notice the "this"
document.getElementById('usernameError').innerHTML = "Invalid username";
return false;
}
return true;// allow submission
}
}
I've had similar issues to this in the past myself.
When you click the 'Login' button of your form, you are triggering two separate events - Calling of the 'validateForm();' javascript function, and submission of the form itself. The problem here, is that submitting the form involves the browser sending an outbound request back to the form target, and to my knowledge, there is no way, using javascript, to kill a request event once it has been triggered.
Using 'onsubmit=return false;', likely, is doing exactly what it is supposed to do - Exiting the current javascript scope (and therefore preventing further javascript associated to that particular event from executing). However, unfortunately, the submission of the form itself, while possible to trigger and control via javascript, is not actually handled by javascript and is not a javascript function itself.
What I've found, in my experiences, to be the best solution, is to use the 'button' type input instead of the 'submit' type input - Both 'submit' and 'button' appear as buttons, but 'button' doesn't actually have any default inherent associated event action (therefore, doesn't actually do anything when you click on it) - What this means, is that, via event handlers (such as 'onclick', as you've done), you are able to entirely control what happens when a user clicks on a 'button'.
You haven't included your 'validateForm();' javascript function here, so I don't know what it contains, but, if it doesn't already do so, I'd include code to submit the form via that javascript function, submitting the form once validation has been successful (or returning some sort of human readable error if validation fails) - That combined with using 'button' instead of 'submit' should solve your problem.
Hope this helps. :)
Edit: Thought of this shortly after making my initial reply. Some browsers will process events handlers such as 'onclick' prior to submitting forms via the submit input type; However, I've found that certain older browsers do not do this currently (thus context of my above post). For newer browsers that honour the results of event handlers processed prior to form submission, it should be possible to prevent the second event (form submission) from occurring at all if validation fails; However, not all browsers honour these results, and I've found that some will continue to submit the form regardless of those results.
well thanks u all, so finally I found the solution by your ideas here is what I have done
rather putting return formvalidate(); function I put it in submit onclick event and it run like charm... thanks
<div style="margin-left: 55px;">
<input class="btn" style="width: 80px;" type="reset" name="reset" value="Reset" onclick="clearFields()"/>
<input class="btn" style="width: 80px;" type="submit" name="submit" value="Login" onclick="return validateForm();"/>
</div>
this is the javascript
function validateForm(){
var form = document.forms['loginForm'];
if(document.getElementById('loginName').value == "")
document.getElementById('usernameError').innerHTML = 'Invalid username or email';
else{
form.submit();
}
return false;
}

Sending html form data as JSON to PHP using JQuery/AJAX

When i click my login button, it just reloads the page for some reason. it should alert the string i echo from my php page.
This is my login.js code:
$(document).ready(function(){
$('#login').click(function(){
$('#msgLoginStatus').show();
$('#msgLoginStatus').html("processing...");
$.post('login.php',{username:"bob",password:"pass"}, function(data){
alert(data);
});
});
});
my login.php:
<?php
echo "message";
?>
and my form:
<form id="loginForm" action="" method="post">
<fieldset id="body">
<fieldset>
<label for="username">Username</label>
<input type="text" name="username" id="username" />
</fieldset>
<fieldset>
<label for="password">Password</label>
<input type="password" name="password" id="password" />
</fieldset>
<button id="login">login</button>
<label for="checkbox"><input type="checkbox" id="checkbox" />Remember me</label>
<br />
<p id="msgLoginStatus" style="display:none"></p>
</fieldset>
<span>Forgot your password?</span>
</form>
There are no errors in browser console. I tried this also using $.ajax, it returned an error, i tried putting the error variable in an alert, but when it alerted, it was an empty string. Anyone have an idea whats wrong?
Your login button has an ambiguous action - add type="submit" like this:
<button id="login" type="submit">Login</button>
Now if you really want to execute an explicit POST with JavaScript, call e.preventDefault so the browser's automatic "submit" action will be suppressed.
e.preventDefault();
$.post(...);
But it will probably be better to let the form submit itself. To do this specify the correct action="login.php" attribute in the form:
<form id="loginForm" action="/login.php" method="post">
Keep your existing "click" handler on the login button, just remove the "$.post" part and let the browser handle the posting. You'll still get the nice "processing..." text.
Even better, handle the "submit" event on the form instead of the "click" event on the button:
$('#loginForm').submit(function(e) {
$('#msgLoginStatus').show();
$('#msgLoginStatus').html("processing...");
});
This way you'll get the nice updates whether the user submits the form using the button or by pressing "enter" on the keyboard.
Try:
$('#login').click(function(e){
e.preventDefault();
$('#msgLoginStatus').show();
$('#msgLoginStatus').html("processing...");
$.post('login.php',{username:"bob",password:"pass"}, function(data){
alert(data);
});
});
That prevents a "normal" submit from happening (which, I take, is why you are not getting any errors).
See http://api.jquery.com/event.preventDefault/
Add e.preventDefault(); to the clck handler (and grab the event object in the handler as e).
Or you can Just set the button type = 'Button' and not Submit. THis will also run your code
<button id="login" type="button">Login</button>
In this way you don't have to halt the browser's event

check filename before posting using jquery/ php

I need jquery to check if my posted filename (up_image) is empty or not.
if it's empty i need a div tag to be shown and come with some kind of alert message.
if not, just do the
$("#submit").submit();
<form action="/profile/" method="post" enctype="multipart/form-data" id="submit">
<p>
<label for="up_image">image:</label>
<input type="file" name="up_image" id="up_image" />
</p>
Upload
</form>
$(function() {
$("#post_submit").click(function() {
var fil = $("#up_image");
if($.trim(fil.val()).length == 0) {
alert("Choose a file!");
fil.focus();
return false;
}
$("#submit").submit();
});
});
1: use a standard submit button to submit your form rather than a javascript-dependent link, for accessibility reasons, and to prevent brokenness if someone tries to right-click-open-in-new-window or other similar action on the link. If you want it to look like a link, you can still use a button, just apply some CSS to make it no longer look like a button.
2: use the form.onsubmit event to do validation rather than relying on a submit button click (forms can also be submitted by pressing enter, which may not always generate a button click)
<form id="uploadform" method="post" action="/profile/" enctype="multipart/form-data">
<p>
<label for="up_image">image:</label>
<input id="up_image" type="file" name="up_image" />
</p>
<p>
<input type="submit" value="Upload" />
</p>
</form>
<script type="text/javascript">
$('#uploadform').submit(function(e) {
if ($('#up_image').val()=='') {
alert('Please choose a file to upload.');
e.preventDefault();
}
});
</script>

Categories