PHP/JavaScript form validation? - php

I'm new with PHP and JavaScript. I eant to validate form, and if the form input fields are correct, then send it to php external script. I've tried something like this:
<head>
<script type="text/javascript">
function Validate(){
var x=document.forms["form"]["firstname"].value;
var y=document.forms["form"]["lastname"].value;
var z=document.forms["form"]["age"].value;
if(x==null || x=="") {
alert("Input name!");
} else if(y==null || y=="") {
alert("Input surname!");
} else if(z==null || z=="") {
alert("Input age!");
} else {
// IS IT POSSIBLE TO SEND FORM HERE FORM VARIABLES TO PHP SCRIPT?
}
}
</script>
</head>
<body>
<form name="forma" action="validate.php" method="post" onSubmit="return Validate()">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
Age: <input type="text" name="age">
<input type="submit">
</form>
</body>
</html>

Since you are not returning false from your function, the form should be being submitted anyway. You can stop it from being submitted by having your validate() function return false.

Your code looks correct, other than the fact you probably want to return false on failure to prevent the form from submitting. When not returning false, the form will simply continue to submit.
I also think you probably meant to name your form form not forma

You should validate the input server-side (php), even if you did it client-side (javascript).
You do this by checking on $_POST in validate.php:
Quite at the beginning of your script:
if (isset($_POST)) { // form has been sent
if (!isset($_POST['firstname']) || strlen($_POST['firstname'])==0) { // no entry
$e['firstname']='please enter a firstname!'; // prepare error-msg
}
if (!isset($e)) { // no error, continue handling the data
// write data to database etc.
}
}
// in your form...
if (isset($e)) echo "there were errors: ". implode(',',$e);

You need to put this code:
function Validate(){
var x=document.forms["form"]["firstname"].value;
var y=document.forms["form"]["lastname"].value;
var z=document.forms["form"]["age"].value;
if(x==null || x=="") {
alert("Input name!");
return false;
} else if(y==null || y=="") {
alert("Input surname!");
return false;
} else if(z==null || z=="") {
alert("Input age!");
return false;
} else {
return true;
}
}

Related

Contact form - Passing variables from PHP to jQuery

[I suspect the issue at hand has to do with how the php array gets passed to jQuery, if that isn't the case I apologize for the misleading title]
The contact form below is working -- except when I submit the forms' data, sometimes one field always keeps its red border indicating missing input, even when it actually has data.
To elaborate: I have a working php-only solution but on submit it causes a page-reload which I would like to avoid. After some research, it seems I need php/jQuery/ajax to perform these things asynchronously and to stay on the same site.
Desired behaviour:
So there are three required input fields called name, email and message, if any one is left out, it should receive a red border and no email gets sent.
Actual behaviour:
If for example only name and message are filled out and submitted, the empty email field is colored red.
But if a (valid) email is provided, the second submit action does not remove the red border around the email field.
I know that javascript and friends is a client-side language, and PHP gets processed server-side. Once the form is submitted, the .ajax function takes the serialized form values, uses 'POST' to stuff it into the php script and waits for the server to call us back inside .done()
This is where I'm lost - how is the php array to be used in jQuery?
E.g. no matter what, this line is never reached:
console.log("All fields filled and valid");
index.html:
<!DOCTYPE html>
<head>
<meta http-equiv="content-type" content="text/html" charset="UTF-8" />
<script src="jquery-1.12.4.min.js"></script>
<script src="verify.js"></script>
<style>
.input-error
{
border: 2px solid red;
}
</style>
<script>
$(document).ready(function() // Wait until website (DOM) is completely loaded
{
/* Page top */
$('#pagetop').click(function()
{
console.log(this);
$('body, html').animate({scrollTop: '0px'}, 600);
return false;
});
});
</script>
</head>
<body>
<!-- action is left blank as process.php is called from verify.js -->
<form action="" method="POST" id="contactForm">
<label for="company">Company</label>
<br>
<input type="text" style="width: 904px; height: 24px;" id="company" name="company" value="">
<br><br>
<label for="name">Name *</label>
<br>
<input type="text" style="width: 904px; height: 24px;" id="name" name="user_name" value="">
<br><br>
<label for="email">Email *</label>
<br>
<input type="text" style="width: 904px; height: 24px;" id="email" name="user_email" value="">
<br><br>
<label for="message">Message *</label>
<br>
<textarea style="width: 904px; resize: none;" rows="9" id="message" name="user_message"></textarea>
<br><br>
<input type="submit" id="submit" name="submit" value="Send">
<br><br>
</form>
</body>
verify.js
$(document).ready(function()
{
// process the form
$('#contactForm').submit(function(event)
{
//$('#name, #email, #message').removeClass('input-error');
// process the form
$.ajax(
{
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : $('#contactForm').serialize(),
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data)
{
// log data to the console so we can see
console.log(data);
if (data.errors.name)
{
console.log("Name missing");
$('#name').addClass('input-error');
}
else
{
$('#name').removeClass('input-error');
}
// handle errors for email
if (data.errors.email)
{
console.log("Email missing or invalid");
$('#email').addClass('input-error');
}
else
{
$('#email').removeClass('input-error');
}
// handle errors for message
if (data.errors.message)
{
console.log("Message missing");
$('#message').addClass('input-error');
}
else
{
$('#message').removeClass('input-error');
}
if(data.input_valid == true)
{
console.log("All fields filled and valid");
alert('success');
}
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
process.php
<?php
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// Sanitize input variables
$company = test_input($_POST['company']);
$name = test_input($_POST['user_name']);
$email = test_input($_POST['user_email']);
$message = test_input($_POST['user_message']);
// Validate the variables
// If any of these variables don't exist, add an error to our $errors array
if (empty($name))
$errors['name'] = 'Name is required.';
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL))
$errors['email'] = 'Valid Email is required.';
if (empty($message))
$errors['message'] = 'Message is required.';
$from = '--- Contact Form ---';
$to = 'some#mail.com';
$subject = 'Message from Contact Form';
$body = "From: $name\nCompany: $company\nE-Mail: $email\nMessage:\n\n$message";
// return a response ===========================================================
// if there are any errors in our errors array, return a success boolean of false
if(!empty($errors))
{
// if there are items in our errors array, return those errors
$data['input_valid'] = false;
$data['errors'] = $errors;
}
else
{
// If there are no errors process our form, then return a message
$data['input_valid'] = true;
if(mail($to, $subject, $body, $from))
{
$data['message'] = 'Thank you for your message!';
$data['mail_sent'] = true;
}
else
{
$data['message'] = 'Message could not be sent - please try again later.';
$data['mail_sent'] = false;
}
}
// return all our data to an AJAX call
echo json_encode($data);
// Convert special characters to html entities to prevent XSS attacks
// Also remove white-space and backslashes
function test_input($val)
{
$val = trim($val);
$val = stripslashes($val);
$val = htmlspecialchars($val);
return $val;
}
?>
It looks like if all validations pass in your php script, then data['errors'] is never defined. This might cause an error to be thrown (that you can see in the browser console) in the javascript when you write:
if (data.errors.name)
data.errors will evaluate to undefined in javascript, and when you try to access a property of undefined like data.errors.name, it will throw an error and stop the script.
To fix this, you probably just need to define errors in your php script, (though I'm not 100% sure the JSON methods won't leave out an empty array...). Try doing this in your php script:
if(!empty($errors))
{
// if there are items in our errors array, return those errors
$data['input_valid'] = false;
$data['errors'] = $errors;
}
else
{
// If there are no errors process our form, then return a message
$data['input_valid'] = true;
$data['errors'] = $errors; // even though it is empty
// etc
EDIT:
I don't know if it will work with your jquery version but just in case it doesn't, place this code in your header:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
I used the below code and it worked. Sent the email without having to change the PHP code:
$(document).ready(function() {
$('#contactForm').submit(function(event) {
$.ajax({
type: 'POST',
url: 'process.php',
data: $('#contactForm').serialize(),
dataType: 'json',
encode: true
})
.done(function(data) {
console.log(data);
if(data.input_valid == true) {
console.log("All fields filled and valid");
// If the function is a success remove error classes from all fields
// you can either place the below code above the alert so that it happens
// before you get the success message, or after.
$('#name').removeClass('input-error');
$('#email').removeClass('input-error');
$('#message').removeClass('input-error');
alert('success');
} else {
if (data.errors.name) {
console.log("Name missing");
$('#name').addClass('input-error');
} else {
$('#name').removeClass('input-error');
}
if (data.errors.email) {
console.log("Email missing or invalid");
$('#email').addClass('input-error');
} else {
$('#email').removeClass('input-error');
}
if (data.errors.message) {
console.log("Message missing");
$('#message').addClass('input-error');
} else {
$('#message').removeClass('input-error');
}
}
});
event.preventDefault();
});
});

PHP form processing using JQuery not Working

I'm processing a form using PHP and JQuery and it's not processing the way it should normally process. My HTML is:
<form action="" method="POST" name="forgot_pass_form">
<label><h3>Please Enter your email!</h3></label><br>
<input type="text" name="email_pass" id="email_pass" />
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
My JQuery code which is in the same page as HTML code:
<script type="text/javascript">
$(document).ready(function($) {
var email = $('#email_pass').val();
$("#submit").live('click', function(){
$.post('email_password.php',
{
'email_pass' : email
},
function(data) {
alert(data);
});
return false;
});
});
</script>
My PHP code which is on email_password.php:
<?php
$email = $_POST['email_pass'];
if(empty($email)){
echo 'empty';
} else {
echo 'Not';
}
?>
The problem here is it always alert me with empty even if I've entered something in the text box
I even tried this way:
if(empty($_POST)){
echo 'empty';
} else {
// process the form
$email = $_POST['email'];
if(empty($email)){
echo 'Email is empty';
} else {
echo 'Email is not empty';
}
}
By trying this way, it alerts me with Email is empty. Please help
When you try to capture a field value, it must be the same name. The name you have in your form is 'email_pass' and in your PHP code you are waiting for 'email'
This should be:
if(empty($_POST)){
echo 'empty';
} else {
// process the form
$email = $_POST['email_pass']; // The field form name
if(empty($email)){
echo 'Email is empty';
} else {
echo 'Email is not empty';
}
}
Sorry for my english :s
use this code
<script type="text/javascript">
$(document).ready(function($) {
$("#submit").live('click', function(){
var email = $('#email_pass').val();
$.post('email_password.php',
{
'email_pass' : email
},
function(data) {
alert(data);
});
return false;
});
});
</script>
The issue is that your making a $_POST call with jQuery and in that function you "post" under the new name email_pass. Update your PHP file to reference $_POST['email_pass'] and you'll be good to go.
Use 0n() and get email value inside the click function
<script type="text/javascript">
$(document).ready(function($) {
$("#submit").on('click', function(){
var email = $('#email_pass').val();
$.post('email_password.php',
{
'email_pass' : email
},
function(data) {
alert(data);
});
return false;
});
});
</script>

validate form before submition

I want to submit a form with php variables to input into javascript, the problem is that the variables are only set after posting, which is too late for them to be echoed into the javascript. Of course, if I then submit again, the variables have been implemented into the javascript and it works as it should. However, I would prefer just to submit once.
Is there any way to validate the form before submission ? Here is an example of my dilemma:
<?php
if(isset($_POST['submit'])){$name=$_POST['name'];}
?>
<html>
<div id="message"></div>
<form action="home.html" method="POST">
<input type="text" name="name">
<input type="submit" name="submit" value="conditions-met"
onclick=<?php if($name=="bob"){echo"start();";}?>>
</form>
</html>
<script type="text/javascript">
function start(){
document.getElementById('message').innerHTML = 'hello bob';
return true;
}
</script>
Man people are mean to you!!
Basically you should validate the fields using JavaScript.
When the submit button is clicked do the checks. Continue on success, show an error message on failure.
example
<form id="myForm" onsubmit="return ValidateFields(this)" name="myForm" accept-charset="UTF-8" enctype="multipart/form-data"" action="myPhpScript.php" method="POST">
// html fields
</form>
<script>
function ValidateFields(formObject)
{
var FieldsValid = true;
//Validate the fields and if one of them is not valid set FieldsValid to false
if(!FieldsValid )
{
//show an error message
return false; // Returing false will prevent the form from submitting
}
return true;// the form will be submitted
}
</script>
In order to become a ninja please read the following:
http://www.script-tutorials.com/form-validation-with-javascript-and-php/
http://www.webcredible.co.uk/user-friendly-resources/dom-scripting/validate-forms-javascript.shtml
http://www.w3schools.com/js/js_form_validation.asp
<html>
<div id="message"></div>
<form action="home.html" method="POST" onsubmit="return validate()">
<input type="text" name="name" id="name">
<input type="submit" name="submit" value="conditions-met" >
</form>
</html>
<script type="text/javascript">
function validate(){
name=document.getElementById('name').value;
if(name == "")
{
document.getElementById('message').innerHTML = 'Please Fill Name';
return false;
}
return true;
}
</script>
You can do it with Ajax and beforeSubmit function with Jquery You have:
$.ajax({
url: "your async page in php",
cache: true,
data: $("#formID").serialize(),
type: 'POST',
beforeSend: function(){
/* You can validate your input here*/
},
success: function(response){
/* Based on the response from php you can handle the message to the user*/
},
error: function(response){/*Error Handler*/},
complete: function(){/*If it's complete than you can reset the form*/}
});
I think it's easy and more clear if you use cross Ajax/PHP request
The function bound to the onclick-event must return true if validation is correct, or false otherwise.
The same function must be in javascript. You cannot call a php function in it. If you want php, try ajax.
<input type="submit" onsubmit="return validate();" />
<script>
function validate() {
// do validation in javascript
// or make an ajax request e.g. to
// /validate.php?name=somename&surname=someothername
// and let this request answer with true or false
// return true if valid, otherwise false
}
</script>

Form Validation using JavaScript and html

i want to validate my form.I have a form validation javascript code in my code igniter view but it is not working and still sending values to next page without any validation.Could you tell me where I am making mistake and why this is happening?
Code:
<form method="get" action="/calculator/stage_two" name="calculate" id="calculate" onsubmit="return validateForm();">
<div class="calc_instruction">
<input type="text" name="property_number" placeholder="No/Name" id = "property_number" class="stage_one_box" />
<input type="text" name="postcode" placeholder="Postcode" id = "postcode" class="stage_one_box" />
</div>
<input type = "image" name = "submit_calculator" id = "submit_calculator" value="Go" src = "/images/next_button.png" />
</form>
Javascript function:
<script type="text/javascript">
function validateForm() {
var postcode=document.forms["calculate"]["postcode"].value;
if (postcode==null || postcode=="") {
alert("Please enter the postcode to give you more accurate results");
document.forms["calculate"]["postcode"].focus();
return false;
}
</script>
You are missing an end bracket. Any error in the validation code will return a non-false value and allow the submission
Here is a canonical way using forms access:
<form method="get" action="/calculator/stage_two" name="calculate"
id="calculate" onsubmit="return validateForm(this);">
<div class="calc_instruction">
<input type="text" name="property_number" placeholder="No/Name" id = "property_number" class="stage_one_box" />
<input type="text" name="postcode" placeholder="Postcode"
id = "postcode" class="stage_one_box" />
</div>
<input type = "image" name = "submit_calculator" id="submit_calculator" src="/images/next_button.png" />
</form>
<script type="text/javascript">
function validateForm(theForm) {
var postcode=theForm.postcode;
if (postcode.value=="") { // cannot be null or undefined if value="" on field
alert("Please enter the postcode to give you more accurate results");
postcode.focus();
return false;
}
return true; // allow submit
}
</script>
It seems like you are missing the closing braces "}" at the end of the function.
<script type="text/javascript">
function validateForm() {
var postcode=document.forms["calculate"]["postcode"].value;
if (postcode==null || postcode=="")
{
alert("Please enter the postcode to give you more accurate results");
document.forms["calculate"]["postcode"].focus();
return false;
}
} // <-- here
</script>
Please Add end braces for function
<script type="text/javascript">
function validateForm()
{
var postcode=document.forms["calculate"]["postcode"].value;
if (postcode==null || postcode=="")
{
alert("Please enter the postcode to give you more accurate results");
document.forms["calculate"]["postcode"].focus();
return false;
}
}
</script>
in your javascript function closing brace is missing
Please use this
in your javascript closing brace is missing
<script type="text/javascript">
function validateForm()
{
var postcode=document.forms["calculate"]["postcode"].value;
if (postcode==null || postcode=="")
{
alert("Please enter the postcode to give you more accurate results");
document.forms["calculate"]["postcode"].focus();
return false;
}
}
</script>
Try simply this line
var postcode=document.getElementById("postcode").value;
instead of
var postcode=document.forms["calculate"]["postcode"].value;
and
postcode==undefined
instead of
postcode==null
and for function validateForm() { you are missing the closing }
Try insert debugger here and try go throw method
<script type="text/javascript">
function validateForm() {
debugger;
var postcode=document.forms["calculate"]["postcode"].value;
if (postcode==null || postcode=="")
{
alert("Please enter the postcode to give you more accurate results");
document.forms["calculate"]["postcode"].focus();
return false;
}
In the code you posted, you are missing a closing brace for your validateForm() function, so assuming that's your actual code, what's happening is that you get a JavaScript error on submit, which causes the browser to just post the form.

jQuery focus / blur $_GET['variable'] conflict

I have a simple focus / blur. 'Name of Venue' is shown by default since it's the value of the input type. on 'focus' it hides and on 'blur' is shows again if there's no text.
Here's the input field
<input type="text" name="name" id="search_name" value="Name of Venue" maxlength="100" />
Here's the jQuery
$('#search_name').focus(function() {
if($(this).val() == 'Name of Venue') {
$(this).val('');
}
});
$('#search_name').blur(function() {
if($(this).val() == '') {
$(this).val('Name of Venue');
}
});
On submit I don't want 'Name of Venue' to be stored as the get variable for $_GET['name']. So, I'm doing <br /><br /> PHP
if($_GET['name'] === 'Name of Venue') {
$_GET['name'] = '';
}
But, this doesn't work. How can I make it so the get variable will be empty on submit if it's the default value?
Consider using the HTML5 placeholder attribute if possible. The value will be blank if nothing was entered.
<input type="text" name="search_name" id="search_name" placeholder="Name of Venue" maxlength="100" />
It will appear/disappear automatically, so you won't need the focus/blur code. Also, "name" is a bad name for name, I'd use something more unique (usually the id will do).
As an alternative, you could do this:
<form id="myform" method="get" action="">
<input type="text" name="search_name" id="search_name" value="Name of Venue" maxlength="100" />
<input type="submit" id="submit_button" value="Submit" />
</form>
<script src="jquery-1.7.1.min.js"></script>
<script>
// ready() not need if <script> follows content, but best to put this in a .js file and link in <head>
$(document).ready(function() {
// Define once and you're good
var search_name = $('#search_name');
var submit_button = $('#submit_button');
var search_default = 'Name of Venue';
search_name.focus(function() {
if($(this).val() == search_default) {
$(this).val('');
}
});
search_name.blur(function() {
if($(this).val() == '') {
$(this).val(search_default);
}
});
$("#myform").submit(function(event) {
if (search_name.val() == '' || search_name.val() == search_default) {
event.preventDefault();
} else {
return true;
}
});
});
</script>
<?php
var_dump($_GET);
$name = '';
if (isset($_GET['search_name'])) {
// Without the check, we might run query when none exists
$name = $_GET['search_name'];
$name = $name != 'Name of Venue' ? $name : '';
}
var_dump($name);
?>
This will prevent a submit with a blank or default name. It's probably handy to put any repeated logic in a function and call those when handling the GET in PHP with any extra search variables.
You can control the value on client side and if it's a required field don't let the form to be submitted. If it's not required, just set the value to "" if it is "Name of Venue".
I think you have to make the field value blank before submitting the form if value is Name of Venue.
$('#frName').submit(function() { if($('#search_name').val() == 'Name of Venue' ){ $('#search_name').val('') } return false;});
You can remove return false if you want to submit the value. Hope its helps you

Categories