I am trying to track the fields that are left blank on my website form when it is submitted.
The form I am using is used by my sales agents, and since I do not immediately see the submitted info before the sales agent has a chance to modify the submitted information, I am looking to see if they are filling out all of the info on the site instead of adding in more info later in the CRM. This will help me to optimize the form for their use. Currently the form is written using HTML, PHP, jQuery and AJAX.
I have not tried anything yet, as I do not even know where to begin with this. I have not seen it done before.
Let me know if you need to see the markup or if this question needs more clarification. Feel free to point me in the direction of a tutorial if that is easiest.
Thanks for the help!
That is what PHP empty() is for:
if (empty(trim($_POST['some_field']))
{
// Nothing was supplied.
}
So, you could create an array of 'required' fields like this:
$required = array('this', 'that', 'the', 'other');
...and then loop through them:
$errors = false;
foreach ($required as $field)
{
$field_value = isset($_POST[$field]) ? trim($_POST[$field]) : null;
if (empty($field_value))
{
$errors[] = 'The "' . $field . '" field was not submitted.';
}
}
if ($errors)
{
// Do something now that you know there are missing fields.
// Here, we're sending an email...
$subject = 'These fields were not filled out';
$body = 'The following errors occurred: ' . implode(', ', $errors);
mail('email#example.com', $subject, $body);
}
I think that you want to know the way how to check and validate the form information before submit. And as you said that you use jQuery, so I advise that there are 2 solutions to solve the problem at least.
1, write the validate script by yourself.
you can use the following script to check the form data before submit.
jQuery(form).submit(function(){
// Here you can validate your form data
// and if the data are incorrect,
// you can return false, and the form submission will be cancelled
});
2, use the jQuery Validation plugin.
The plugin can be got from http://jqueryvalidation.org/, and you can import it with the following script.
<script type="text/script" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.js"></script>
And then, you only need to add some special attribute in your form.
For example, if you add "required" of your input field, which means the field must be filled with the characters.
<form>
<input type="text" name="username" required />
</form>
And then, write the following script to notify the plugin to validate the form before submission.
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("form").validate();
});
</script>
You can check in both PHP or JS. If you want to do this server side so you can save this information simply check the POST results of the form.
if (trim($_POST['myField'])=="") {
//not filled out. if you have default values, check for it in the if above too.
mail('your#email.com', 'Subject', 'Your body.');
}
Related
Basically I'm using this tutorial: HTML FORM
Everything is working as it should but one flow I've found is that everyone can see the URL for your .php which in this case is "url: "contact_mail.php""
Is there a way to protect my form from blank submission when someone type the url and just press enter.
Example: www.mywebsite.com/contact_mail.php
Thank you!
First you can use the required attribute on mandatory fields for client-side:
<input type="text" name="mandatory_field" required>
But you will need to verify server-side in case the user modified the form. You can use empty() on any variable ($_POST or $_GET):
if (empty($_POST['mandatory_field'])) {
// print error message or redirect to form page
}
You can use isset() to verify if a field is submitted. Your validation could be:
if (!isset($_POST['mandatory_field']) || empty($_POST['mandatory_field'])) {
// print error message or redirect to form page
}
Other cases:
If all fields are mandatory you could check with in_array():
if (in_array(false, $_POST)) {
// print error message or redirect to form page
}
If doing various data validation here is what I use to do with forms:
$errors = [
'empty field' => empty($_POST['field']),
'another error message' => $another_condition
];
if (in_array(true, $errors)) {
$error_message = array_search(true, $errors);
// print or redirect, and you can tell the user what is wrong
}
Say you have the following form;
<form action="savething.php" method="GET" name="mythingform">
<input name="thing1" type="text" />
<input name="thing2" type="text" />
<input type="button" value="Submit" onclick="validateAndSubmit()" />
</form>
In this, instead of a submit type input, I have used a button. This means, something needs to happen before the page will submit, so, for example;
<script>
function validateAndSubmit()
{
var thing1 = document.getElementsByName("thing1")[0];
var thing2 = document.getElementsByName("thing2")[0];
if (thing1.value.length > 0 && thing2.value.length > 0)
{
document.forms["mythingform"].submit();
}
}
</script>
The JavaScript function here will only call the submit on the form when the inputs are not empty
In terms of stopping someone from accessing this without permission;
<?php
if (!isset($_REQUEST['myvariable'] || empty($_REQUEST['myvariable']))
die("Please make sure the form has been submitted properly with all required information");
Using die in this, will terminate execution of the script any further, you can also use exit and both allow you have have a "termination message" attached to them as part of the stoppage process
$_REQUEST isn't the safest of options, but it permits you to use GET or POST methods from forms to be able to retrieve and use data
Form blank submission you can use java-script validation or jquery validation validation or you can also use php validation to avoid blank form submission.
core js validation
simple example:
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
jquery validation
validation library
https://jqueryvalidation.org/documentation/
example:
$("#myform").validate({
submitHandler: function(form) {
// some other code
// maybe disabling submit button
// then:
$(form).submit();
}
});
I hope it helps.
(1) there should be no danger from someone 'just entering' the URL in their browser - the back-end code is supposed to respond only to POST, not to GET (entering a URL in a browser makes it issue a GET request for the given URL).
(2) the quoted example code already includes client-side validation (including checks for empty fields), so if someone legitimately uses your entry form, they will not be able to send a blank form.
(3) all that remains is to protect the back-end code from accidental or malicious posting of empty forms (and any other use that is undesirable). The example PHP code doesn't have any checks, you should add some - like the isset(...) or empty() checks suggested in another answer here).
Use if (empty($_POST['your_field']))
So if a post or get query reaches your php script, empty will check if the field is empty or not.
So something like this:
if (empty($_POST['your_field'])) {
echo 'Field xxx should not be empty';
}
Although isset would be better, since if they just go to the link, your POST and GET variables are empty.
So something like this is kinda foolproof:
if (!isset($_POST['your_field']) || empty($_POST['your_field'])) {
echo 'Field xxx should not be empty';
}
Didn't think i'd need a separate piece of code for GET, but ok.
if (!isset($_GET['your_field']) || empty($_GET['your_field'])) {
echo 'Field xxx should not be empty';
}
hi i am trying to carry out dynamic checks on my registration form, so when the user enters information, the php code is checking it for errors.currently, i am only trying to pass the values back to jquery to be displayed on the form, i have not yet carried out any validation on the input boxes. i can only seem to pass one value back, as soon as i try and pass multiple values, nothing gets returned, any help would be mostly appreciated.
You should send the whole form if you want to validate multiple inputs at once to your php.
Your validate function should look something like
function validate(fname, lname){
$.post('php/registration.php', $("form").serialize(), function(data){
$('#fname_feedback').text(data.fname);
$('#lname_feedback').text(data.lname);
},'json');
}}
And your php function could be something like (until you do the validation)
$return_data=$_POST;
header('Content-Type: application/json');
echo json_encode($return_data);
exit();
}
I am trying to add a CAPTCHA option to a specific page on a website. The validation code for the page is written in Javascript, and the PHP CAPTCHA documentation (http://www.phpcaptcha.org/documentation/quickstart-guide/) is given strictly in PHP. I've managed to add the CAPTCHA box to the page and everything else up until where the code verifies the user's CAPTCHA entry. I am having trouble merging the two because:
a) they are written in different languages
b) my knowledge in PHP/Javascript is very basic
Here is a snippet of the page's original validation code:
function validate(formData, jqForm, options){
// # Valid?
valid = false;
// # Validate Contact Form
var errs = new Array();
// # Contact Name
if($('#ContactName').val() == ''){
errs.push(['#ContactName', 'Enter your name.']);
} else if(label = $('#ContactNameLabel label.error-message')){
label.fadeOut();
}
I want to repeat the same process except with the user's CAPTCHA entry. The following code is given in the PHP CAPTCHA documentation:
include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
$securimage = new Securimage();
and
if ($securimage->check($_POST['captcha_code']) == false) {
// the code was incorrect
// you should handle the error so that the form processor doesn't continue
// or you can use the following code if there is no validation or you do not know how
echo "The security code entered was incorrect.<br /><br />";
echo "Please go <a href='javascript:history.go(-1)'>back</a> and try again.";
exit;
}
The code can be found, along with instructions, in the link given above. My question is: how can I implement the given PHP code inside the Javascript function that I have? To my understanding, it is possible to embed PHP inside Javascript as long as the forum is written using PHP (and I can confirm that the website I'm working on is built using CakePHP) - I am just lost with the syntax/how to go about executing this (if it is possible).
If anyone could offer me a helping hand that would be greatly appreciated! Thank you in advance.
You can write PHP within JavaScript if the JavaScript is in the View (as opposed to being in a .js file)
Example:
<?php
$message = "Hello World";
?>
<script>
alert("<?php echo $message; ?>");
</script>
You can't do that as PHP is a server-side language and Javascript is a client-side one. By the time your browser sees the page, all the PHP processing has finished on the server and all that's left is client-side rendering of the page. You will need to validate the CAPTCHA on the server-side.
I've got a form that can optionally be pre-populated via facebook connect. Once a user connects, their name and email are automatically filled in. The problem is that this doesn't trigger the remote validation to check if the email already exists.
Is there a way I could call the validation on that field alone? Something like:
$('#email-field-only').validate()
would be idea. Searched through the docs with no luck.
This method seems to do what you want:
$('#email-field-only').valid();
Edit
API has changed, see Paul's answer.
Use Validator.element():
Validates a single element, returns true if it is valid, false
otherwise.
Here is the example shown in the API:
var validator = $( "#myform" ).validate();
validator.element( "#myselect" );
.valid() validates the entire form, as others have pointed out. The API says:
Checks whether the selected form is valid or whether all selected
elements are valid.
$("#FormId").validate().element('#FieldId');
For some reason, some of the other methods don't work until the field has been focused/blured/changed, or a submit has been attempted... this works for me.
$("#formid").data('validator').element('#element').valid();
Had to dig through the jquery.validate script to find it...
If you want to validate individual form field, but don't want for UI to be triggered and display any validation errors, you may consider to use Validator.check() method which returns if given field passes validation or not.
Here is example
var validator = $("#form").data('validator');
if(validator.check('#element')){
/*field is valid*/
}else{
/*field is not valid (but no errors will be displayed)*/
}
When you set up your validation, you should be saving the validator object. you can use this to validate individual fields.
<script type="text/javascript">
var _validator;
$(function () {
_validator = $("#form").validate();
});
function doSomething() {
_validator.element($('#someElement'));
}
</script>
-- cross posted with this similar question
in case u wanna do the validation for "some elements" (not all element) on your form.You can use this method:
$('input[name="element-one"], input[name="element-two"], input[name="element-three"]').valid();
Hope it help everybody :)
EDITED
$("#element").validate().valid()
I trying to implement reCAPTCHA in one of my forms,...but i am using ajax as the submission. (More specifically the prototype ajax.updater)
Once I submit and error check my form I try to load the reCAPCHTA widget thingy (in my updated div element) which basically just calls a javascript file like so:
<script type="text/javascript" src="http://api.recaptcha.net/challenge?k=6Le6SwUAAAAAAIWm8wCRFd8SrI-H0R1Yx4Tkw2Ks"></script>
However the JS file is not being read?...and i've tried all combination of evalScripts:true and evalJS:'force' etc. in the ajax.updater.....however i don't think I have a very good understanding of why the js file isn't processing :(
If anyone can shed some light on this issue I will be very appreciative.
Thanks, Andrew
This doesn't address your exact problem, but 'Dark Side of the Carton' has some excellent code for validating reCAPTCHA via jQuery AJAX which might help.
In summary:
Add the following Javascript:
$(function() {
function validateCaptcha() {
var challengeField = $('input#recaptcha_challenge_field').val(),
responseField = $('input#recaptcha_response_field').val();
// alert(challengeField);
// alert(responseField);
// return false;
var html = $.ajax({
type: 'POST',
url: 'ajax.recaptcha.php',
data: "recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField,
async: false
}).responseText;
if (html.replace(/^\s+|\s+$/, '') == "success") {
$('#captchaStatus').html(' ');
// Uncomment the following line in your application
return true;
} else {
$('#captchaStatus').html(
'Your captcha is incorrect. Please try again'
);
Recaptcha.reload();
return false;
}
}
// Modified as per comments in site to handle event unobtrusively
$('#signup').submit(function() {
return validateCaptcha();
});
});
Then add the ajax.recaptcha.php file which: "outputs only the word “success” if the captcha matches and a message and the response from reCaptchta if it fails. This is important because we are looking for the word success in our validateCaptcha() function."
require_once('/inc/recaptchalib.php');
$publickey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'; // you got this from the signup page
$privatekey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$resp = recaptcha_check_answer(
$privatekey,
$_SERVER['REMOTE_ADDR'],
$_POST['recaptcha_challenge_field'],
$_POST['recaptcha_response_field']
);
if ($resp->is_valid) {
?>success< ?
} else {
die(
"The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")"
);
}
The example is in PHP, but I adapted it easily to work with Zope/Python
Be careful using any sort of client-side script, such as JavaScript, for validation. You have no control over the end-user's browser. The purpose of a CAPTCHA is to prevent automated submissions of a form. Anyone sophisticated enough to set that up isn't going to have a problem overriding your JavaScript validation and CAPTCHA checking. For example, they could set validateCaptcha() to always return true, bypassing your careful checks - or just disable JavaScript.
That being said, there's nothing wrong with performing the entire form submission with ajax and using the results of the CAPTCHA check to determine if the form gets processed or not.
The important point is that the decision of whether or not to handle the form has to be made on the server-side, not the client-side.
Why client-side validation is not enough
to answer my own question...
there is a reCAPTCHA AJAX api....which is pretty easy way to get around this problem:
link text
Also,..the documentation on the http://www.prototypejs.org/api/ajax/updater site.....talks about the evalscript option and how is only puts any javascript through the native eval() function....which kind of screws me over trying to implement error checking with WMD...but that's another story.
Andrew
If that's the literal code snippet you're using, you haven't closed the tag... so it wouldn't be evaluated.
call Recaptcha.reload(); on callback event in your Ajax code., it will reload new Recapcha every time that Ajax submitted
Hi Friend i found the answer
https://developers.google.com/recaptcha/docs/display?hl=es#AJAX
And in this how validate
http://blog.reaccionestudio.com/comprobar-recaptcha-con-ajax-usando-jquery/
Success for you
Securing AJAX calls with reCaptcha
function performAJAX() {
let captcha = $('[name=g-recaptcha-response]');
$.ajax({
url: 'ajaxHandler.html',
data: {
captcha: (captcha.length?captcha[0].value:''),
// other data fields
},
});
}
I have had similar issues with getting reCaptcha to play nicely when loaded into the page using jQuery's .load() method. Here is a page that has a novel solution: http://www.maweki.de/wp/2011/08/recaptcha-inside-a-with-jquery-ajax-or-load-dynamically-loaded-object/
Basically the reCaptcha API uses document.write method to display the reCaptcha. When you get jQuery invloved this won't work. Use this PHP code in place of loading recaptcha.js
<?php
$api = file_get_contents('http://www.google.com/recaptcha/api/js/recaptcha_ajax.js');
$api = str_replace('document.write','$("body").append',$api);
echo $api;
?>
It just does a find for document.write and replaces it with $(selector).append.
Made my implementation work.