javascript and php validation? - php

I have some javascript and php code written to validate a field. Both codes are to validate whether the field is not empty, is within a limit of 35 characters and contains only alphabetic characters and a hyphen(-). What i want to do is for both the javascript and php to validate simultaneously and show they're messages for entering incorrect data but it only seems that the javascript is validating properly due to the fact that an alert pops up but no message is shown from the php side. Here is my code :
<script type="text/javascript">
function validateFamily()
{
var family=document.getElementById('family');
var stringf = document.getElementById('family').value;
var ck_password = /^[A-Za-z-]/;
if (family.value=="")
{
alert("Family name must be filled out");
return false;
}
else if (document.getElementById('family').value.length > 35)
{
alert("Family name cannot be more than 35 characters");
return false;
}
else if(!ck_password.test(stringf))
{
alert("Family name can only contain alphabetic characters and hypehns(-)");
return false;
}
return true;
}
</script>
<?php
if (isset($_POST['submit'])) {
$flagf = false;
$badcharf = "";
$stringf = $_POST["family"];
$stringf = trim($stringf);
$lengthf = strlen($stringf);
$strmsgf = "";
if ($lengthf == 0) {
$strmsgf = '<span class="error"> Please enter family name</span>';
$flagf = true;}
else if ($lengthf > 35) {
$strmsgf = '<span class="error"> Can not enter more than 35 characters</span>';
$flagf = true;}
else {
for ($if=0; $if<$lengthf;$if++){
$cf = strtolower(substr($stringf, $if, 1));
if (strpos("abcdefghijklmnopqrstuvwxyz-", $cf) === false){
$badcharf .=$cf;
$flagf = true;
}
}
if ($flagf) {
$strmsgf = '<span class="error"> The field contained the following invalid characters: '.$badcharf.'</span>';}
}
if (!$flagf) {
$strmsgf = '<span class="error"> Correct!</span>';}
}
?>
<form name="eoiform" method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="eoi" onsubmit="return validateFamily() && validateGiven() && validateMaleFemale() && validDate() && validateAddress() && validatePost() && validateParent() && validateWork() && validateHome() && validateMob() && validateCheckBoxes() && validateTextBoxes();">
<b>Student's Family Name</b>
<br>
<input type="text" id="family" name="family" /><?php echo $strmsgf; ?>
<input type="submit" name="submit" id="submit" value="submit" />
</form>
Could anyone help me with this?

Your JavaScript and PHP cannot execute simultaneously because the former happens in the user's browser before the form is POSTed and the latter happens after this once the form has reached the server.
You can verify this by inspecting the source code of your webpage in the browser: there's no PHP!
If your JavaScript makes the catch, nothing is sent to the server because you return false. In practice it makes sense to have the server-side checks in place in case:
Someone is tricky and modifies the form after it's validated but before it's sent.
JavaScript is disabled or breaks for some reason.

The way this form works is that you have a JS function in the form's onsubmit property which can prevent the form's submission if a value is wrong. If your JS function returns false because of an error, the form will never be submitted.
In order to get the functionality you want, you need to perform the checks on the server side only, but you'll need to submit the form each time for that to occur...
An alternative way would be to check the entered values when the user finishes adding a value to each of your text fields, i.e. attach a JS function to the fields' blur() property, and make an AJAX call to your server that will validate the field contents before the form is actually submitted.
You can use jQuery's validate plugin for more complex validations, if these can be done on the client side, as well:
http://jqueryvalidation.org/

As paislee stated there is no way you can simultaneously run php and javascript. There are however dynamic requests you can send to run some php code and it's called AJAX. This will also not ensure an absolutely accurate simultaneous execution but will be closer to what you aim for.

Related

Changing action based on input value using PHP

I'm working on a form that I'd like to change the form action based off of the value of an input on form submit. This needs to be accomplished using PHP.
Here's what I've tried so far:
<?php
$action = "";
$input = (isset($_POST["hp"]));
if($input == "") {
$action = "action1";
} else {
$action = "action2";
}
?>
<form name="contactForm" id="contactForm" method="post" action="<?php echo $action; ?>">
<!-- form stuff here -->
<input id="hp" name="hp" type="text" class="hp"/>
<input type="submit" name="submit" id="submit" value="Submit Query" class="button" />
</form>
This doesn't work because the hp field for (isset($_POST["hp"])) doesn't have a value from the get-go, so it always goes to action1.
I've also tried:
<?php
if(isset($_POST['submit'])){
$input = ($_POST['hp']);
$action = "";
if($input == "") {
$action = "action1";
} else {
$action = "action2";
}
}
?>
<form name="contactForm" id="contactForm" method="post" action="<?php echo $action; ?>">
That didn't work because Perch (the CMS this is being built on) throws you an error that $action isn't defined yet.
And when I tried:
<?php
$action = "";
if(isset($_POST['submit'])){
$input = ($_POST['hp']);
if($input == "") {
$action = "action1";
} else {
$action = "action2";
}
}
?>
It didn't do anything at all on submit because it set the action as "".
Any suggestions?
To write in short way
$action = isset($_POST['hp'])?'action2':'action1';
That's all.
Differents possibilities:
Same action and redirect
The most easy way probably is send form to the same PHP file, and in this file, get the content of this input via POST and redirect to the correct file.
Prevent default submit and add submit event via JavaScript
The second option, may be add an event to form on submit via JavaScript, prevent default action to prevent the submit, then check value of input, set action and submit form:
<form name="contactForm" id="contactForm" method="post" action="">
...
</form>
<script>
document.querySelector('#contactForm').addEventListener('submit', function(e) {
//Prevent default submit
e.preventDefault();
//Check input value
if (...) {
this.action = "page1.php";
} else if (...) {
this.action = "page1.php";
}
//perform submit form.
this.submit();
});
</script>
Use data binding library
This is probably the best form to do it, but the most complicated to understad, this form is based of use a data binding library like Vue.js, KnockoutJS or RactiveJS to set in model object the action string depending of input value.
Then, in HTML form tag, set in action the value of model data using the binding syntax of the chosen library:
//Vue.js syntax
<form name="contactForm" id="contactForm" method="post" :action="action">
//Ractive.js syntax
<form name="contactForm" id="contactForm" method="post" action="{{action}}">
What do I recommend?
If you're novel with PHP and don't know JavaScript, the first option is probably the best for you, if you If you know JavaScript and you know how to work with events, but never used a binding library, probably the second option is more recommended for you.
If you worked with some data binding library (or framework that implements data binding like Angular), the third options is probably the best for you.
If the 2nd and 3rd versions don't work, you must be missing an input like:
<input type="submit" name="submit">
You can either add that button to the form, or you can change your code to use if isset($_POST['hp'])
<?php
$action = "";
if(isset($_POST['hp'])){
$input = ($_POST['hp']);
if($input == "") {
$action = "action1";
} else {
$action = "action2";
}
}
?>
None of the answers above worked for me, so here is what I ended up going with.
Use Case:
I have a "Search" form with two fields. When a user clicks "Search",
these values should be added to the URL, so that previous searches
may be bookmarked. The search should then be performed.
When the page is first loaded or no search criteria are used, all
possible results should be shown.
Code description:
At the top of the file, check if the user submitted the form.
If so:
get the values from the fields you want and save them to local variables.
navigate to the same PHP file, this time passing the variables you are interested in
If the user did not submit the form:
check for URL parameters
If there are URL parameters present, save them to local variables,
and use these local variables to run the search
Code Snippet:
if(isset($_POST['submit'])){
if(!empty($_POST['projectNameSearch'])){
$projectNameSearch = mysqli_real_escape_string($conn, $_POST['projectNameSearch']);
}
if(!empty($_POST['projectDescriptionSearch'])){
$projectDescriptionSearch = mysqli_real_escape_string($conn, $_POST['projectDescriptionSearch']);
}
if($projectNameSearch != '' || $projectDescriptionSearch != ''){
header("Location: projects.php?projectnamesearch=$projectNameSearch&projectdescriptionsearch=$projectDescriptionSearch");
}
} else {
if(isset($_GET['projectnamesearch'])){
$projectNameSearch = mysqli_real_escape_string($conn, $_GET['projectnamesearch']);
}
if(isset($_GET['projectdescriptionsearch'])){
$projectDescriptionSearch = mysqli_real_escape_string($conn, $_GET['projectdescriptionsearch']);
}
}

Sending Form Data Using POST To The Current Page And Another PHP Page At The Same Time

I have seen another person ask this question in stack overflow but I did not get any clear answer/idea from 'his post'. I want to know whether there is a way of sending form data via POST to the current PHP page addstudio.php to verify the entered data & if the entered data is valid it gets redirected to the next PHP page getstudio.php.
To send the form data to the current page I used the following line:-
<form action = "<?php $_PHP_SELF ?>" method = "post">
This is just done to validate the form information and if the form is left blank then a message is displayed in the same PHP page, the code for this is shown below.
<?php
$valid = true;
$studioIdError = $studioNameError = $studioAddressError = $studioPCodeError = $studioTelNoError = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["studioId"])){
$studioIdError = " *This Field Cannot Be Empty";
$valid = false;
}
if(empty($_POST["studioName"])){
$studioNameError = " *This Field Cannot Be Empty";
$valid = false;
}
if(empty($_POST["studioAddress"])){
$studioAddressError = " *This Field Cannot Be Empty";
$valid = false;
}
if(empty($_POST["studioPCode"])){
$studioPCodeError = " *This Field Cannot Be Empty";
$valid = false;
}
if(empty($_POST["studioTelNo"])){
$studioTelNoError = " *This Field Cannot Be Empty";
$valid = false;
}
}
?>
To the above code I want to know if there is a way I can get the getstudio.php page to run when $valid = true.
I cannot use the code include 'getstudio.php'; because I want getstudio.php to run on a seperate page.
I cannot use the code header("Location:getstudio.php");exit(); to run either because the values in the global array $_POST[] is not sent to the PHP page like it is when the page is called directly from the form (Eg:- <form action = 'getstudio.php' method = 'post'>).
Is there a way of running the getstudio.php page while sending the values stored in the $_POST[] array to the getstudio.php page when $valid = true?
You have a few options.
Use AJAX to validate the form; then, if valid, do the submit.
Store the data somewhere client-side or server-side between pages (cookies or sessions).
Send a specially-crafted html that makes the browser to mimic a user sending a form. [ugly, the user sees a redraw]
Keep both validation and processing in the same page (why separate?).
In any case don't forget to re-validate before acting upon user data, unless absolutely sure the data can't be affected by a user (in the list above, only when storing data in a session, and still not recommended). Then, if validating again anyways, why bother with a separate page?
So as i understand you want to send Data first Addstudio.php than Getstudio.php but you want second one with redirection.
Make your HTML like this :
<form action="getstudio.php" method="POST">
<!-- etc -->
</form>
Make your Javascript like this (include jQuery):
$(".your-form-class").on('submit',function(evt){
evt.preventDefault();
var instance = $(this);
var formData = new FormData($(".your-form-class")[0]);
$.ajax({
type:"POST",
data:formData,
url:"addstudio.php",
success:function(response){
instance.submit();
}
});
});
Here is your current page
<?php
$_POST["studioName"] = 'testdata';
$valid = true;
if(empty($_POST["studioName"])){
$studioNameError = " *This Field Cannot Be Empty";
$valid = false;
}
// send data to getstudio.php if valid
if($valid){ ?>
<form method="post" action="getstudio.php" id="senddata">
<input type="hidden" name="postdata" value="<?php print_r($_POST); ?>">
</form>
<script>
document.getElementById("senddata").submit();
</script>
<?php } ?>
Here is your getstudio.php file to receive validated post data
<?php
echo '<pre>';
print_r($_POST['postdata']);
die;

Registration form validating errors

If I submit blank fields it still adds it into database. I made a loop to check if everything is on place but it keeps redirecting it to error page. I've been struggling with this almost 2 hours but cant find a solution.
Links are here since i can post more than 2 :
Try to set
Don't allow nulls
in the column property of table. It can be done during the table design or Edit table Design in the database.
Hope this helps.
You using empty(). http://us3.php.net/empty
This only returns false if NULL, FALSE, or not exists, NOT if empty string.
You should be doing this:
foreach($required as $post){
if ($_POST[$post] == "") {
die(header("refresh:0.5;url=error.php"));
}
}
However, I don't know why you don't just put this over the entire code block so it only gets executed on submit of the form. Then you don't have to keep rechecking it.
if (isset($_POST)) { //or a specific $_POST variable if multiple submit paths
//code here
}
Additionally, you should edit your question to include the relevant code in the question or in the future, searchers may discover that your pastebin link no longer works.
I think in any way you should make some client-side validation on empty field like jQuery functions :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("form").submit(function(){
if($("#first_name").val() == ''){
alert("First name cann't be empty");
return false;
}else if($("#last_name").val() == ''){
alert("Last name cann't be empty");
return false;
}else if($("#email").val() == ''){
alert("Email cann't be empty");
return false;
}else if($("#password").val() == ''){
alert("Password name cann't be empty");
return false;
}
});
});
</script>
You're trying to get indexes on $_POST array that doesn't exist, so correct your $required array and put fields names not the variables names, just like this in process.php:
$required = array('first_name','last_name','password','email');
foreach($required as $post){
if($post = empty($_POST[$post]) || $_POST[$post] == ""){
die(header("refresh:0.5;url=error.php"));
} elseif($required != empty($_POST)) {
echo "";
}
}
I think yor a looking for something like,
if(isset($_POST['field1']) && !$_POST['field1'] =="")
{
//your codes goes here
}
Maybe You have done something like
<input type=text name=name1 value ="" />
If so, Please do it like,
<input type=text name=name1 />
This will not send name1 to your page;

alert message on submit if text box is empty using PHP

How to prevent a form from submit if text box is empty?
This I have done in JSP successfully using alert message.
Javascript:
function validate()
{
var x=document.forms["Form1"]["comp"].value;
if (x==null || x=="")
{
alert("comp cannot be blank");
return false;
}
<form name="Form" action="welcome.php" onsubmit="return validate()" method="post">
<input type="text" name="comp">
How can I do the same using PHP? So that whenever a user submits without entering text it should give message to user through an javascript alert() message.
I can display alert message:
echo '<script language="javascript">alert("comp cant blank");</script>';
But how can i give condition?what are the changes has to be made in the above please put it in a code form.i have to do it only in PHP.
You cannot stop a form from submitting using PHP.
PHP is server side, you would need to have Javascript to handle the form submit if there is an issue with your validation. You should handle validation on both client side (JS) and server side (PHP).
So no, not possible with just PHP as you outlined, the form WILL submit, then you validate it. Can't stop it with PHP (as its just HTML to the user).
you can used from this jquery code:
$("#btnSubmitID").click(function(event){
if($("#txtID").val()==''){
event.PreventDefault();
alert("your message");
}
});
this is a sample, you can validate your form with this way before post to the server.
You could submit the form using XHR (known as AJAX) and have php verify the data.
You would still need to submit the XHR using javascript.
Your javascript code looks fine and it should not submit the form when its empty. However, if you want to do from PHP code, you can do the same, but the form needs to submit and return back to same page when its not valid (or empty).
Here is sample code
<?php
if ($_POST['comp'] == '')
{
header("location:yourpagename");
}
else
{
// process
}
?>
And now for the non-pseudo code answer. This is working, tested code that elaborates on the concepts I already posted.
<?php
function formWasPosted()
{
return array_key_exists( 'comp', $_POST );
}
// -------
function validate( &$errors )
{
if ( $_POST['comp'] == '' )
{
$errors['comp'] = 'cannot be blank';
}
return count( $errors ) == 0;
}
// -------
function getError( $fieldName, $errors )
{
$out = '';
if ( array_key_exists( $fieldName, $errors ) )
{
$out = '<span class="errorMsg">' . $errors[$fieldName] . '</span>';
}
return $out;
}
//------------------------------------------------------------------------
// $errors will be passed to our validate function so we can set error messages per field if desired.
$errors = array();
$formMsg = '';
if ( formWasPosted() )
{
if ( validate( $errors ) )
{
// do processing here
header( 'Location: http://www.example.com/success' );
exit();
}
$formMsg = '<div class="errorNotice">There were problems with your submission</div>';
}
?>
<html><head>
<script type="text/javascript">
function validate()
{
var x=document.forms["Form1"]["comp"].value;
if (x==null || x=="")
{
alert("comp cannot be blank");
return false;
}
}
</script>
<style>
.errorMsg, .errorNotice { color: red; }
.errorNotice { font-size: 150%;}
</style>
</head>
<body>
<?php echo $formMsg; ?>
<form name="Form" action="welcome.php" onsubmit="return validate()" method="post">
<label for="comp">Comp <?php echo getError( 'comp', $errors ); ?></label>
<input id="comp" type="text" name="comp">
</form>
</body>
</html>
Here is the general approach I use for processing forms.
Pseudo code:
Has Form Been Submitted?
Is form valid?
process form (db insert/update/delete, other operation here
Else
Print form with error messages and optionally a javascript alert
End is form valid
Else
Print form without error messages
End has form been submitted

What's wrong with this PHP/JavaScript form validation?

I’m not sure whether the problem I’m having is with JavaScript or with PHP.
My objective: To validate a simple yes no form using JavaScript then process it via PHP and have a message displayed.
My problem: When JavaScript is enabled and I click the radio button and submit it the PHP doesn’t output “YES status checked”. Instead it refreshes the page (ie. I think it simply posts the form to user_agreement4.php and does nothing else) When JavaScript is disabled and I click on the YES radio button and submit it, the message “YES status checked” displays correctly. Please note that the code below is for user_agreement4.php. The form will be submitted to itself.
What am I doing wrong?
Please note that this is unfinished code-I haven't added things like cookies, redirection etc. yet.
Also I have a question about choosing answers. May I choose more than one reply as an answer?
<?php
// Set variables
$selected_radio = 'test';
session_start(); // start up your PHP session!
// The below code ensures that $dest should always have a value.
if(isset($_SESSION['dest'])){
$dest = $_SESSION['dest'];
}
// Get the user's ultimate destination
if(isset($_GET['dest'])){
$_SESSION['dest'] = $_GET['dest']; // original code was $dest = $_GET['dest'];
$dest = $_SESSION['dest']; // new code
}
else {
echo "Nothing to see here Gringo."; //Notification that $dest was not set at this time (although it may retain it's previous set value)
}
// Show the terms and conditions page
//check for cookie
if(isset($_COOKIE['lastVisit'])){
/*
Add redirect >>>> header("Location: http://www.mywebsite.com/".$dest); <<This comment code will redirect page
*/
echo "aloha amigo the cookie is seto!";
}
else {
echo "No cookies for you";
}
//Checks to see if the form was sent
if (isset($_POST['submitit'])) {
//Checks that a radio button has been selected
if (isset($_POST['myradiobutton'])) {
$selected_radio = $_POST['myradiobutton'];
//If No has been selected the user is redirected to the front page. Add code later
if ($selected_radio == 'NO') {
echo "NO status checked";
}
//If Yes has been selected a cookie is set and then the user is redirected to the downloads page. Add cookie code later
else if ($selected_radio == 'YES') {
echo "YES status checked";
// header("Location: http://www.mywebsite.com/".$dest);
}
}
}
?>
<HTML>
<HEAD>
<TITLE>User Agreement</TITLE>
<script language="javascript">
function valbutton(thisform) {
// validate myradiobuttons
myOption = -1;
for (i=thisform.myradiobutton.length-1; i > -1; i--) {
if (thisform.myradiobutton[i].checked) {
myOption = i;
}
}
if (myOption == -1) {
alert("You must choose either YES or NO");
return false;
}
if (myOption == 0) {
alert("You must agree to the agreement to download");
return false;
}
thisform.submit(); // this line submits the form after validation
}
</script>
</HEAD>
<BODY>
<H1> User Agreement </H1>
<P>Before downloading you must agree to be bound by the following terms and conditions;</P>
<form name="myform" METHOD ="POST" ACTION ="user_agreement4.php">
<input type="radio" value="NO" name="myradiobutton" />NO<br />
<input type="radio" value="YES" name="myradiobutton" />YES<br />
<input type="submit" name="submitit" onclick="valbutton(myform);return false;" value="ANSWER" />
</form>
</BODY>
</HTML>
See this line:
if (isset($_POST['submitit'])) {
If the user presses the submitit button, and javascript is disabled, everything works as expected - the button inserts its name/value pair into the posted data right before the form gets posted, so $_POST['submitit'] is set.
If, however, javascript is enabled, the button doesn't trigger a postback itself, instead it calls a javascript function which posts the form. Unfortunately though, when you call form.submit(), it won't go looking for buttons and add their name/value pairs to the posted data (for various reasons). So you need to find a different way of telling whether you are processing a post-back; the easiest way is to just put a hidden field into your form and check for that, e.g.:
(in the HTML part, somewhere inside the <form></form>):
<input type="hidden" name="is_postback" value="1" />
...and then change your PHP check to:
if ($_POST['is_postback'] == '1')
Change your javascript to:
function valbutton(thisform) {
// validate myradiobuttons
myOption = -1;
for (i=thisform.myradiobutton.length-1; i > -1; i--) {
if (thisform.myradiobutton[i].checked) {
myOption = i;
}
}
if (myOption == -1) {
alert("You must choose either YES or NO");
return false;
}
if (myOption == 0) {
alert("You must agree to the agreement to download");
return false;
}
return true; // this line enables the form to submit as normal and is not actually required
}
And remove the "return false;" from the on click event of the button. Having the validation function return false on validation fail is sufficient to stop the from from validating.
This should enable your php to work as is.

Categories