Form validated but still submitting without values? - php

im using javascript validation to check for values within each form field before the form sends to the database but when i click submit the form still sends even without any values.
To test it i clicked on each of the fields to clear them and then tried submittin the button
here is the form
<form method="post" action="send.php" id="theform" name="theform">
<input type="text" name="firstname" id="firstname" value="First Name" onFocus="this.value=''" class="yourinfo" ><br/>
<input type="text" name="lastname" id="lastname" value="Last Name" onFocus="this.value=''" class="yourinfo"><br/>
<input type="text" name="email" id="email" value="Email Address" onFocus="this.value=''" class="yourinfo"><br/>
<div id="datepicker"></div>
<input type="hidden" name="date" id="date">
<input type="image" src="images/sbmit-button.png" name="submit" height="49" width="190" id="submit" value="submit" style="margin-top:10px; margin-left:-2px;" >
</form>
heres the javascript
$(document).ready(function(){
// Place ID's of all required fields here.
required = ["firstname", "lastname", "email"];
// If using an ID other than #email or #error then replace it here
email = $("#email");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
$("#theform").submit(function(){
//Validate required fields
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("needsfilled");
}
}
// Validate the e-mail.
if (!/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("needsfilled");
email.val(emailerror);
}
//if any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
return false;
} else {
errornotice.hide();
return true;
}
});
// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){
if ($(this).hasClass("needsfilled") ) {
$(this).val("");
$(this).removeClass("needsfilled");
}
});
});
im also linking to a jquery file:
<script type="text/javascript" src="js/jquery-1.5.1.min.js"></script>
ive tested it on its own and it seems to work but something seems to be over riding it and skipping past the validation in this page
==================================================================================
i still not working... basicallly do u think it might have something to do with the jquery UI datepicker that im also using with the form?? ive not included that in the form validation as i only wanted to make sure the firstname, lastname and email was filled out
i have this included in my form page:
<script>
$(function() {
$("#datepicker").datepicker({
altField: '#date'
});
$('#submit').click(function() {
$('#output').html($('form').serialize());
});
});
</script>
would this be having an effect of it submitting even though there are no values in the fields?
something is definatley overriding the validation and submitting it

It's working for me! (but it's probably not working how you imagine it should)
Once you enter a valid email, the form is sent if you hit submit. Why? Because you have already filled in firstname and lastname for the user - with the strings First Name and Last Name!
So you shouldn't just check for empty or error string filled first and last names, but you should also trigger an error if the first name is First Name or the last name is Last Name.
// Check for empty value, the error string
// OR the default values of "First Name" and "Last Name"
if ((input.val() == "") ||
(input.val() == emptyerror) ||
(input.val() == "First Name") ||
(input.val() == "Last Name")) {
input.addClass("needsfilled");
Working example
(I assume you use server side validation as the final check, since people like me just love NoScript. )
(Also you declare 5 global variables at the top of your code and one more global in your for loop (i)... don't forget var.. just like you used for input)

What if I disabled JavaScript? You should (also) validate on the server side.
Also refactor your code! You can start with extracting methods.

You need to cancel the submit event. It looks like you're trying to do this with a return false or a return true. However, with jQuery you'll need to do it a slightly different way.
First, you'll need to have an argument name for the JavaScript event. I typically use e.
$("#theform").submit(function(e){
Then you'll need to update the following code as follows:
//if any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
e.preventDefault();
} else {
errornotice.hide();
}
The e.preventDefault() stops the event from being processed. In this case, that means the form will not be submitted.

Related

How can I create a custom form in WordPress?

I have a WordPress site and would like to create a form (input → database).
I've seen two tutorials:
How you can easily create customized form in WordPress
How to create custom forms in WordPress without using plugins?
They're both very similar. Creating the front end with HTML and JavaScript, and then processing the information to the database using PHP.
My problem is that whenever I submit the form, it shows a 404 page which says:
Oops! That page can’t be found.
Now my problem is (or I want to know):
Where do I need to put the process.php file? (I'm using FileZilla). I've tried several places in the public_html/wp-content folder.
Why aren't the name and email fields being validated? (no alert for empty name field, etc.)
Form structure:
Your Name: [TEXT], Your Email: [TEXT], Sex: [*male *female], Your Age:[TEXT], [Submit Button]
Form page:
<form name="myForm" method="POST" onsubmit="return form_validation()" action="../process.php">
Your Name: <input id="customer_name" name="customer_name" type="text" />
Your Email: <input id="customer_email" name="customer_email" type="text" />
Sex: <input name="customer_sex" type="radio" value="male" />Male <input name="customer_sex" type="radio" value="female" />Female
Your Age: <input id="customer_age" name="customer_age" type="text" />
<input type="submit" value="Submit" />
</form>
<script type="text/javascript">
function form_validation() {
/* Check the Customer Name for blank submission */
var customer_name = document.forms["myForm"]["customer_name"].value;
if (customer_name == "" || customer_name == null) {
alert("Name field must be filled.");
return false;
}
/* Check the Customer Email for invalid format */
var customer_email = document.forms["myForm"]["customer_email"].value;
var at_position = customer_email.indexOf("#");
var dot_position = customer_email.lastIndexOf(".");
if (at_position < 1 || dot_position < at_position + 2 || dot_position + 2 >= customer_email.length) {
alert("Given email address is not valid.");
return false;
}
}
</script>
File process.php (not edited):
<?php
$customer_name = $_POST["customer_name"];
$customer_email = $_POST["customer_email"];
$customer_sex = $_POST["customer_sex"];
$customer_age = $_POST["customer_age"];
$conn = mysqli_connect("Database Host", "Database Username", "Database Password", "Database Name");
if(!$conn) {
die(‘Problem in database connection: ‘ . mysql_error());
}
$query = "INSERT INTO ‘Database Name’.’Table Name’ ( ‘customer_name’, ‘customer_email’, ‘customer_sex’, ‘customer_age’ ) VALUES ( $customer_name, $customer_email, $customer_sex, $customer_age )";
mysqli_query($conn, $query);
header("Location: my-site.com/success"); // Redirects to success page
?>
To answer question one: WordPress provides action and filter hooks for developers to add their custom PHP code or functions. You should look into that, because using plugins that produce snippets will not help in your case, because it causes your PHP code to execute without even loading your form, so you will be seeing your success page instead.
To learn more about action and filter hooks visit here.
Alternatively to us action/filter hooks, you can upload your PHP file into the theme folder. However, there's a flaw to that. Your file may be lost when WordPress updates.
To answer question two: There is an easier way to validate your form if using JavaScript. All you need to do is add the word 'required' within the input tag. You can also use input type 'email' together with the required keyword to validate you email. See the example below.
<form name="myForm" method="POST" action="../process.php">
Your Name: <input id="customer_name" name="customer_name" type="text" required/>
Your Email: <input id="customer_email" name="customer_email" type="email" required/>
Sex: <input name="customer_sex" type="radio" value="male" />Male <input name="customer_sex" type="radio" value="female" />Female
Your Age: <input id="customer_age" name="customer_age" type="text" />
<input type="submit" value="Submit" />
</form>
If you still want to use your JavaScript function, try using document.getElementById('customer_name') and document.getElementById('customer_email') instead of document.forms. Also make sure you close your script tag at the end. See below for an example.
<script type="text/javascript">
function form_validation() {
/* Check the Customer Name for blank submission */
var customer_name = document.getElementById('customer_name').value;
if (customer_name == "" || customer_name == null) {
alert("Name field must be filled.");
return false;
}
/* Check the Customer Email for invalid format */
var customer_email = document.getElementById('customer_email').value;
var at_position = customer_email.indexOf("#");
var dot_position = customer_email.lastIndexOf(".");
if (at_position < 1 ||
dot_position < at_position + 2 ||
dot_position + 2 >= customer_email.length) {
alert("Given email address is not valid.");
return false;
}
}
</script>

Form still returning true value even there's empty()

I'm having a problem for doing my form .
When I click the button generate , I'm attempting to redirect to an error page but it stills redirect to the correct page even in the form it's empty.
if(isset($_POST['Generate'])) {
if(!empty($_POST['aid'])) {
$gen_link = "www.correctlink.com";
$_SESSION['active'] = $aid;
header("Location: http://$gen_link") ;
} else {
header("Location : http://error404.com");
}
}
Even when I click the generate button it stills redirect to www.correctlink.com
I want the user to type something in the form
Form Code:
<input type="text" name="aid" id="aid" value="Enter Your Active Here" onfocus=" if (this.value == 'Enter Your Active Here') { this.value = ''; }" onblur="if (this.value == '') { this.value='Enter Your Active Here';} "/><br /><br />
<input type="submit" class="button" value="Generate" name="Generate" id="Generate"/>
The problem here is that you have set a default value of "Enter Your Active Here" in your textbox. If the user simply submits the form without even trying to enter anything in the textbox, the value of $_POST['aid'] becomes "Enter Your Active Here".
So what do you do? Simple, instead of checking for empty, check for
if($_POST['aid'] != "Enter Your Active Here" && ! empty(trim($_POST['aid'])))
Another solution would be to use a placeholder but since that's a HTML5 feature, the compatibility of that across browsers is limited.
EDIT: The second condition is added to make sure the code works in case javascript is disabled on the client machine and the user mischievously tries to submit form by emptying the textbox
If you have the value attribute set to something in the form, it will submit that as the value, therefore it won't be empty. Instead of checking if it's empty, check if it equals Enter Your Active Here.
If you need a placeholder text, you could use the attribute placeholder instead of value.
The $_POST['aid'] is not empty because you set value for this as Enter Your Active Here
Use something like this
<input type="text" name="aid" id="aid" placeholder="Enter Your Active Here" .......
OR
<label>Enter Your Active Here</label><input type="text" name="aid" id="aid" .....
replace
if(!empty($_POST['aid']))
by
if($_POST['aid']!="" && $_POST['aid']!="Enter Your Active Here")
Thanks.

Jquery returning ObjectObject, first two fields return as expected

I was wondering if someone could help me out as I have googled for quite a while today, and haven't found anything to solve my problem.
The websites I've looked at mentioned it's because it's returning JSON, but they are getting it on all the fields, not just the one.
But what I can't understand, is why isn't the first two fields as well? Hence my confusion
I am submitting a login form, using Jquery and AJAX (I'm knew to this).
The first two fields (email and pass) submit, and return as expected.
For testing purposes I simply return their values in <span id="loginresponse"></span>.
I have a third field, to prevent CSRF, called 't' (named it random names, to see if this was the problem - I still get [object Object] returned). <input type="hidden" name="t" value="RandomToken"/>
When submitting the form, I expect it to return what I entered into the fields - "Email,Pass and RandomToken".
Instead, I get Email,Pass,[Object Object].
Here is my DoLogin function, which is called when the form is submitted.
function DoLogin()
{
var Email = $("#email").val();
var Pass = $("#pass").val();
var LoginResponse = $("#loginresponse");
var T = $("#t");
var EmailPlaceholder="Email address";var PassPlaceholder="Your password here";
$.get('path/to/login_ajax.php?email='+Email+'&pass='+Pass+'&t='+T, function(data)
{
$('#loginresponse').html(data);
});
/*if(Email != EmailPlaceholder && Pass != PassPlaceholder && Email != "" && Email != " " && Pass !="" && Pass != " ")
{
}*/
}
Here is my HTML form:
<form action="javascript:DoLogin();" method="post"><!--Also tried changing method to GET, still got the same problem -->
<input id="email" class="inputemail" type="text" name="email" size="40" value="Email address" onclick="$(this).val('');"/><span>Your email</span><br/>
<input id="pass" class="inputpassword" type="password" name="pass" size="40" value="Your password here" onclick="$(this).val('');"/><span>Your password</span><br/>
<input id="t" type="hidden" name="t" value="RandomToken"/>
<input class="indexsubmit" type="submit" value="Login"/>
</form>
<span id="loginresponse"></span>
And finally, login_ajax.php
<?php
echo $_GET['email'].$_GET['pass'].$_GET['t'];
?>
As mentioned above - I am only echoing the results, for know, as I'm knew to Jquery and AJAX, so I want to check if all fields are returning the values as expected, and one isn't...The token field.
You are chaining the object T of the input element and not the element's value to the query string of your GET request.
You should change this line
var T = $("#t"); // The object of the input element
to this
var T = $("#t").val(); // The value of the input element
Maybe what you want is:
var T = $("#t").val();

Displaying error/success messages inside an input field

I have an input field that asks for an email address followed by a submit button. Here is the code associated with that:
HTML
<div class="email">
<form action="handler.php" method="post" id="hgb-signup">
<input type="text" name="email" id="email" value="Enter your email address">
<input type="submit" name="submit" id="submit" value="»" />
</form>
</div>
JAVASCRIPT
Event.observe(window, 'load', function() {
jQuery('#email').focus(function() {
jQuery(this).val('');
});
jQuery("#hgb-signup").submit(function(e){
var dataString = jQuery(this).serialize();
jQuery('#email').val('Sending... please wait...');
jQuery.getJSON('handler.php?callback=?', {
"sent_data": dataString },
function(received_data) {
jQuery('#email').val(received_data.message);
}
);
e.preventDefault();
});
});
Right now, when the page loads the #email input field reads "Enter your email address". When you click on the submit button, it overwrites the #email value with "Sending... please wait..." and depending on whether there's been a problem or the submission was successful, there will be a respective message inside the #email field indicating such. Now, when I click inside the input field, the "Enter your email address" text disappears .val(''), and when I click outside the field, that message is still gone. I initially had a .blur() that put the message back, which is the desired result, however, when users would enter their email address and hit submit, it would submit "Enter your email address" and not the actual email address, because when you hit the submit button .blur() was called.
Now knowing what the goal is, is there a .blur() alternative and if not, how do I best handle this situation?
Basically, here's what I'm looking for:
The #email field should read "Enter your email address" at any given time when the cursor is not inside the field and should come back when the cursor leaves the field, but I would like the error/success message to stay in there after the form has been submitted, unless the user clicks back inside the field and leaves, then it can say "Enter your email address" again.
Thanks!
Use .blur(), but check the val() first. Replace with "Enter your email" only when it's empty
jQuery('#email').blur(function() {
var $this = jQuery(this);
if ($this.val() == '') $this.val('Enter your email');
});
Here's a jsfiddle for you, you can check it out. I also added a check to focus() handler so it would not remove contents when you click on an input field after entering your email.

Text box added using javascript doesnot respond as expected to the js attached to it

I am adding a text box using javascript:
This is what is generated:
<dd id="text3-element" style="width: 350px;">
<input type="text" size="50" id="text3" name="text3" onblur="return getFieldValue(this.id);" value="">
</dd>
This is what is present in the getFieldValue function:
function getFieldValue(id){
var elem = document.getElementById(id);
alert(elem.value);
return false;
}
I'm trying to get the value of the field added using javascript when the value of the filed changes.
However, I keep getting the value as 'undefined', in spite of entering text into the newly added text box.
This does not happen if the form already has a text box to begin with - i.e., if a text box is not being added via a js function.
Anything missing / look wrong here?
Thanks!
I am not sure about the functional requirement, but why don't you just pass the element itself through the function?
<input type="text" onblur="return getFieldValue(this);">
with
function getFieldValue(element){
alert(element.value);
return false;
}
This should work fine.
This worked fine for me on both IE and Chrome. Maybe some other part of the script that you have not posted is throwing the error, can you post the javascript you're using to add the textbox?
You didnt catch if there is no value set for the input
function getFieldValue(element)
{
if (element.value =="") {
alert("Please enter something");
return false;
}
else
{
// make something else
}
}
Test
<input type="text" onblur="return getFieldValue(this);">

Categories