How to do client form data validation in PHP/HTML - php

I have three php files. One is the controller "index.php". One is for displaying output "people.php". The other is a form for user input "form.php"
form.php looks like this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<form action = "" method = "post">
First name: <input name ="first_name" type = "test" size = "55" maxlength = "55"><p>
Second name: <input name ="second_name" type = "text" size = "55" maxlength = "55"><p>
Month: <select name="month">
<option value="">select month</option>
<option value="January">January</option>
<option value="February">February</option>
<option value="March">March</option><p>
<option value="April">April</option><p>
<option value="May">May</option><p>
<option value="June">June</option><p>
<option value="July">July</option><p>
<option value="August">August</option><p>
<option value="September">September</option><p>
<option value="October">October</option><p>
<option value="November">November</option><p>
<option value="December">December</option><p>
</select><p>
Year: <select name ="year">
<option value = ""> -select year-</option>
<option value = "2015"> 2015 </option>
<option value = "2016"> 2016 </option>
<option value = "2017"> 2017 </option>
</select><p>
Date of birth:<input name="date_of_birth" input type="text" id="datepicker"></p>
<input name = "add_person" type="submit" value = "submit">
</form>
</html>
Index.php looks like this:
<?php
if (!isset($_POST['add_person'])){
include 'form.php';
}
elseif (isset($_POST['add_person']) && empty($_POST['first_name']) && empty($_POST['second_name']) && empty($_POST['month']) && empty($_POST['year']) && empty($_POST['date_of_birth'])){
include 'form.php';
}
elseif (isset($_POST['add_person'])){
if (empty($_POST['first_name'])){
exit("First name cannot be left empty");
}
if(empty($_POST['second_name'])){
exit("Second name cannot be left empty");
}
if(empty($_POST['month'])){
exit("month cannot be left empty");
}
if(empty($_POST['year'])){
exit("year cannot be left empty");
}
if(empty($_POST['date_of_birth'])){
exit("date of birth cannot be left empty");
}
$date1 = $_POST['date_of_birth'];
$date2 = date("Y-m-d");
if($date2 < $date1){
exit("Invalid date: Date of birth cannot be in the future");
}
$authors = $_POST['first_name'];
$title = $_POST['second_name'];
$month = $_POST['month'];
$year = $_POST['year'];
echo "$first_name <br> $second_name <br> $month <br> $year <br> $date1";
?>
}
else{
include "form.php";
}
?>
and people.php looks like this:
<html>
<head>
<title></title>
<script>
<!--jquery imebidi(necessary evil)....jquery copy-pasted from here https://jqueryui.com/datepicker/ -->
$(function() {
var date = $('#datepicker').datepicker({ dateFormat: 'yy-mm-dd' }).val();
});
</script>
</head>
<body>
<div id="header">
<div class ="center">
<p>Manuscript management information system</p>
</div>
</div>
<div id="content-wrapper">
<div id="content-main">
<p></p>
<?php
include 'index.php';
?>
<p>
</div>
<div id="content-secondary">
<p>mmmmmmmmmmmmm</p>
</div>
</div>
<div id="sidebar">
<li>Recently published</li>
<li>Submitted to PubCom</li>
<li></li>
</div>
<div id="footer"><p>Welcome</p>
</div>
</body>
</html>
What I'm trying to achieve is to have the error message displayed on the form without having to be transferred to a new page. I mean, if a user fails to enter first name then he/she should get an error on the same form.

You can either add a "required" attribute to every required field :
First name: <input name ="first_name" type = "test" size = "55" maxlength = "55" required>
Or add a "onsubmit" attribute to your form and write a validation scipt in javascript :
<form action = "" method = "post" onsubmit="return validation();">
<script>
function validation(){
if(<conditions>){
return true;
}else{
return false;
}
</script>

you can use HTML 5 Form validation rules . Use the required attribute for getting non empty fields.
<input type="text" name="name" required>
you can also use various input types email, url, number, tel, date to validate specific types . refer this link for more details .
<input type="email" name="email" required placeholder="Enter a valid email address">
other options is to use javascript . check this stackoverflow thread on how to achieve this using jquery .

Related

How to combine two input fields and open as URL for different URL combination?

My website customer frequently looking tracking details, every time they need to go different types courier website and enter tracking id.
All my courier websites tracking url position same, 1) courier website 2) id
eg: (More than one courier service and their respective tracking URL)
1) www.courier.com?trackingid=12345
2) www.courier.in/track/id=1234&type=0&service=0
How to merge two input fields.
eg:
Code :
<!DOCTYPE HTML>
<html>
<body>
<form action="#" method="post">
Select Courier :
<select name="courier">
<option value="">--Please choose an option--</option>
<option value="professional_courier">Professional Courier</option>
<option value="india_post">India Post</option>
</select>
Trackingid: <input type="text" name="trackingid"><br>
<input type="submit">
</form>
<?php
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);
// if (!empty($_POST)): header("Location: https://www.tpcindia.com/Tracking2014.aspx?id=".$_POST["trackingid"]."&type=0&service=0");
// endif;
if (!empty($_POST['courier']) && !empty($_POST['trackingid'])) {
switch ($_POST['courier']) {
case 'professional_courier':
$url = "https://www.tpcindia.com/Tracking2014.aspx?id=".$_POST["trackingid"]."&type=0&service=0";
break;
case 'india_post':
$url = "https://www.indiapost.gov.in/_layouts/15/dop.portal.tracking/trackconsignment.aspx";
break;
default:
throw new RuntimeException(sprintf('Unknown courier "%s"', $_POST['courier']));
header('Location: ' . $url);
};
};
?>
</body>
</html>
Not working. for single url its working(see below working code),
<!DOCTYPE HTML>
<html>
<body>
<form action="#" method="post">
Select Courier :
<select name="courier">
<option value="">--Please choose an option--</option>
<option value="professional_courier">Professional Courier</option>
<option value="india_post">India Post</option>
</select>
Trackingid: <input type="text" name="trackingid"><br>
<input type="submit">
</form>
<?php
if (!empty($_POST)): header("Location: https://www.tpcindia.com/Tracking2014.aspx?id=".$_POST["trackingid"]."&type=0&service=0");
endif;
?>
</body>
</html>
jQuery solution:
$( "#button" ).click(function() {
var x = $('#select1').val();
var y = $('#select2').val();
window.location.href = 'https://www.' + x + '.com?trackingid=' + y;
});
Hey it is very simple can check this example with PHP code user header location and pass your tracking after post
<!DOCTYPE HTML>
<html>
<body>
<form action="#" method="post">
<select name="cm_id">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
Trackingid: <input type="text" name="trackingid"><br>
<input type="submit">
</form>
<?php if (!empty($_POST)): header("Location: http://localhost/test.php?trackingid=".$_POST["trackingid"]); endif;?>
</body>
</html>
I assume you using jQuery and this is your html form
<form action="#">
<select name="courier" id="courier">
<option value="www.abc.com">ABC</option>
<option value="www.xyz.com">XYZ</option>
</select>
<input type="text" name="tracknumber" id="tracknumber">
<input type="button" id="submit" value="submit">
</form>
To handle what you expect, use on click event jquery
$('#submit').click(function(){
var courier = $('#courier').val();
var tracknumber = $('#tracknumber').val();
window.open(courier+'?trackingid='+tracknumber, '_blank');
});
This is the complete code with multiple courier.
<html>
<head>
<title>Courier Tracking</title>
<script
src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
integrity="sha256-pasqAKBDmFT4eHoN2ndd6lN370kFiGUFyTiUHWhU7k8="
crossorigin="anonymous"></script>
</head>
<body>
<form action="#">
<select name="courier" id="courier" multiple>
<option value="http://example.com">ABC</option>
<option value="http://example2.com">XYZ</option>
</select>
<input type="text" name="tracknumber" id="tracknumber">
<input type="button" id="submit" value="submit">
</form>
</body>
<script type="text/javascript">
$('#submit').click(function()
{
var courier = $('#courier').val();
var tracknumber = $('#tracknumber').val();
$.each(courier, function( index, value ) {
window.open(value+'?id='+tracknumber, '_blank');
});
});
</script>
</html>
Finally working, thanks to everyone.
<!DOCTYPE HTML>
<html>
<body>
<form action="#" method="POST">
Select Courier :
<select name="courier">
<option value="">--Please choose an option--</option>
<option value="professional_courier">Professional Courier</option>
<option value="india_post">India Post</option>
</select>
Trackingid: <input type="text" name="trackingid">
<input type="submit">
</form>
<?php
if (isset($_POST['courier'])) {
if ('professional_courier' === $_POST['courier']) {
header("Location: https://www.tpcindia.com/Tracking2014.aspx?id=" . $_POST["trackingid"] . "&type=0&service=0");
} else if ('india_post' === $_POST['courier']) {
header("Location: https://www.dhl.com/en/express/tracking.html?AWB=" . $_POST["trackingid"] . "&brand=DHL");
}
}
?>
</body>
</html>

html and php form field and submission

I have a short html form and some php code on the same page so that when the form is submitted, the entries appear on the same page. This code works as far as posting the entered information from the form to the page, but I have 2 problems:
The text box for some reason was only letting me enter 1 character, now it won't let me enter any characters.
Every time I refresh the page to try the form again, the information keeps appending. I only want/need for it to show up once after submission.
<form method="post" action="">
<label>Select Out of Office Message
<select name = "selectoutofofficemessage">
<option value = "N/A">N/A</option>
<option value = "Vacation">Vacation</option>
<option value = "Conference">Conference</option>
<option value = "Meeting">Meeting</option>
<option value = "Other">Other</option>
</select>
<label>Custom Out of Office Message
<input type="text" name="customoutofofficemessage" size="30" maxlength="255"/>
</label>
<p>
<input type="submit" name="submit" value="Submit" />
</p>
</form>
<?php
$selectoutofofficemessage = $_POST["selectoutofofficemessage"];
$customoutofofficemessage = $_POST["customoutofofficemessage"];
$posts = file_get_contents("posts.txt");
$posts = "$selectoutofofficemessage - $customoutofofficemessage\n" . $posts;
file_put_contents("posts.txt", $posts);
echo $posts;
?>
Put a validation to the Post values
if(isset(selectoutofofficemessage))
{
execute the html code;
}
else
{
php code....
} then the value will not be repeated again and again and dont append it just display it....
1.First label is incorrect, it doesn't close. Fix it:
<label>Select Out of Office Message
<select>
...
</select>
</label>
2.Change your PHP code:
<?php
$posts = file_exists("posts.txt") ? file_get_contents("posts.txt") : "";
if(!empty($_POST))
{
$selectoutofofficemessage = $_POST["selectoutofofficemessage"];
$customoutofofficemessage = $_POST["customoutofofficemessage"];
$posts = "$selectoutofofficemessage - $customoutofofficemessage\n" . $posts;
file_put_contents("posts.txt", $posts);
}
echo $posts;
Consider each page refresh after a submition causes the last submition.
<form method="post" action="">
<label>Select Out of Office Message</label>
<select name = "selectoutofofficemessage">
<option selected="selected" value="">Select a Message</option>
<option value ="N/A">N/A</option>
<option value = "Vacation">Vacation</option>
<option value = "Conference">Conference</option>
<option value = "Meeting">Meeting</option>
<option value = "Other">Other</option>
</select>
<label>Custom Out of Office Message</label>
<input type="text" name="customoutofofficemessage" size="30" maxlength="255"/>
<p>
<input type="submit" name="submit" value="Submit" />
</p>
</form>
<?php
$posts = file_exists("posts.txt") ? file_get_contents("posts.txt") : "";
if(!empty($_POST))
{
$selectoutofofficemessage = $_POST["selectoutofofficemessage"];
$customoutofofficemessage = $_POST["customoutofofficemessage"];
$posts = "$selectoutofofficemessage - $customoutofofficemessage AT <small><em>". date('h:m A - M-d-Y') ."</em></small> <br>" . $posts;
file_put_contents("posts.txt", $posts);
}
echo $posts;
?>
<?php
if (!empty($_POST)){
?>
<script type="text/javascript">
window.location = window.location.href;
</script>
<?php } ?>

Multistep selectbox in HTML and Javascript

I want to create a html form with 2 nested select box,
And I want to do like that ,
1 selectbox , and user can select
Modern Or Ancient . I did it ;
If User Select ancient , new options are :
Age : (textfield)
Determined By: (text field)
Age By c-14 testing
And,
If C14 testing is performed
Name of the body performing the test
Date of testing
Here's my HTML so far:
<select name="storedinage" id="storedinage" onchange="showfield7(this.options[this.selectedIndex].value)">
<option>Please Select</option>
<option value="Modern" >Modern</option>
<option value="Ancient" >Ancient </option>
and my JavaScript is here:
<script type="text/javascript">
function showfield7(name){
if(name=='Ancient')document.getElementById('div7').innerHTML='Other: <input type="text" name="storedinage" />';
else document.getElementById('div7').innerHTML='';
}
</script>
Check jsfiddle here
I think this is what you wanted. Let me know if otherwise.
I am not sure how your html looks like so I made a bit of my own, please copy what is useful. Don't know either if you want labels on inputs or placeholders, you will have to do those small adjustments.
html
<form action="#" method="post">
<select name="storedinage" id="storedinage" onchange="showfield(this.options[this.selectedIndex].value)">
<option>Please Select</option>
<option value="Modern">Modern</option>
<option value="Ancient">Ancient</option>
</select>
<div id="div7" style="display:none;">
Age:<input type="text" name="storedinage" />
Determined By:<input type="text" name="DeterminedBy" />
Age By c-14 testing?<input type="checkbox" onchange="C14(this)" name="AgeByc-14testing" />
</div>
<div id="C14" style="display:none;">
<input type="text" name="NameBody" placeholder="Name of the body performing the test" />
<input type="text" name="TestingDate" placeholder="Date of testing" />
</div>
</form>
js
function showfield(name) {
console.log('!');
if (name == 'Ancient') {
console.log('passed');
document.getElementById('div7').style.display = 'inline';
} else {
document.getElementById('div7').style.display = 'none';
}
var checkbox = document.getElementById('C14');
if (checkbox.checked == true) {
console.log('true')
}
}
function C14(e) {
if (e.checked == true) {
document.getElementById('C14').style.display = 'inline';
}
}

display the output in the same page using php

im new to php.i created a page in php containing chk boxes ,input fields and retrive the data from the database(mysql) and also use the javascript.
i h've a problem in this ,that is i want to display the output in the same page.
i created the code like this,i want the output in same page,but it shows error.
<?php
if(isset($_POST['submit']))
{
$con=mysql_connect("localhost","demosdef_review","review123");
if(!$con)
{
die('could nt connect 2 the server');
}
mysql_select_db("demosdef_review", $con);
$state = $_POST["state"];
$country = $_POST['country'];
$contry = "USA";
if($country==1)
{
$result = mysql_query("SELECT address FROM storelocator WHERE countryid='1' AND id='$state'");
$row = mysql_fetch_array($result);
echo $row['address'];
}
else
{
$result = mysql_query("SELECT address FROM storelocator WHERE countryid='$country'");
$row = mysql_fetch_array($result);
echo $row['address'];
}
}
?>
enter code here
<div class=buy>
Dealer Enquiry
</div><br/>
<div class=buyfont>Authorized Retailers</div>
<div><img src="images/archivers.png"><br/>
<a href="http://www.archiversannex.com/Books-And-SoftwareSoftware-And-Accessoriesdefault.aspx?PageID=20&CategoryID=48"/>
<img src="images/logo_archivers_annex.png" ></a><br/><br/>
<br/><br/>
</div><br/>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>
<p>
<label for="country" style="padding-right: 2px;">Country</label><select name="country" value="countryid"
id="countryid"
onchange="sub()" style="width:120px;">
<option value="1">USA</option>
<option value="2">CANADA</option>
<option value="3">UK</option>
<option value="4">AUSTRALIA</option>
<option value="5">ITALY</option>
<option value="6">GUATEMALA</option>
<option value="7">NEW ZEALAND</option></select></p>
<p>
<label for="state" style="padding-right: 14px;">State</label>
<select id="state" name="state" value="state" style="width:120px">
<option value="7">Alabama</option>
<option value="8">Alaska</option>
<option value="9">Arizona</option>
<option value="10">Arkansas</option>
<option value="11">California</option>
<option value="12">Colorado</option>
<option value="13">Connecticut</option>
<option value="43">Florida</option>
<option value="14">Georgia</option>
<option value="15">Idaho</option>
<option value="16">Illinois</option>
</select></p> <br/>
<input class="dealer-submit" type="submit" value="Submit" onClick="buy_func()"/>
</form>
<script type="text/javascript">
function sub()
{
var x=document.getElementById("countryid").selectedIndex;
var y=document.getElementById("countryid").options;
var z = document.forms[0].state;
if(y[x].index==0){
z.disabled = false;}
else if(y[x].index>0) {
z.disabled = true;}}
</script>
Your HTML markup has an error
<a href="http://www.hobbylobby.com/storelocator"/>
It should be
<a href="http://www.hobbylobby.com/storelocator">
Also try
<form method="POST" action="">
Keeping the action blank will post it to the same page itself
And replace your submit button with this
<input class="dealer-submit" type="submit" name="submit" value="Submit" onClick="buy_func()"/>
Check the value of the submit button, if its set isset($_GET('submit')) then display the results
does that solve your problem?
submit is the type of the element, 'Submit' is the value you are looking for:
<?php
if(isset($_POST['Submit']){
}
?>
Remove the backslash at the end of the line:
<a href="http://www.hobbylobby.com/storelocator"/>
^

Confused why form is not submitting

I don't think there's anything I left out, but the form doesn't seem to be transmitting any data upon hitting submit. My code is as follows, I realize it's kind of long, but I wanted to include the entire form. All of the attached functions just check if the input was valid:
<form name="formname" id="formname" action="database.php" method = post onsubmit="return checker()">
Username: <input type='text' id='un' onchange="checkname(id)" onkeyup="checkempty(id)" ><div id="un1"></div><br>
Reporter Title:<br>
<select id="s2" onblur="checktype(id)" >
<option value="choose">Choose one</option>
<option value="Assistant Director">Assistant Director</option>
<option value="Director">Director</option>
<option value="DB Admin">DB Admin</option>
<option value="Systems Admin">Systems Admin</option>
</select><div id="s21"></div>
<br>
Password: <input type='password' id='pw' onchange="checkpass(id)" onkeyup="checkempty(id)"><div id="pw1"></div><br>
Email: <input type='text' id='eml'onchange="checkemail(id)" onkeyup="checkempty(id)"><div id="eml1"></div><br>
Description:<br> <textarea rows="6" cols="20" id="desc" onchange="checkdesc(id)" onkeyup="checkempty(id)" ></textarea><div id="desc1"></div><br>
Type of Incident:<br>
<select id="s1" onblur="checktype(id)" >
<option value="choose">Choose one</option>
<option value="afs">afs</option>
<option value="password">password</option>
<option value="hardware">hardware</option>
<option value="other">other</option>
</select><div id="s11"></div>
<br>
<?php
include("connect.php");
$ret = mysql_query("SELECT * FROM countries");
echo "Choose your location:<br>";
echo "<select id='countries' onblur='checktype(id)'>";
echo "<option value='choose'>Choose one</option>";
while($array = mysql_fetch_array($ret)){
echo "<option value='{$array['abbrevs']}'>{$array['full']}</option>";
}
echo "</select><br>";
?>
<div id="countries1"></div><br>
<p>
Would you like an email copy?
<select id="s3">
<option value="no">No</option>
<option value="yes">Yes</option>
</select>
<input type="submit" id = "sub" value= "Submit">
</p>
</form>
and the php I tried to receive it with
<?php
include("connect.php");
$username = $_GET['un'];
$password = $_GET['s2'];
$reporter = $_GET['pw'];
$email = $_GET['eml'];
$description = $_GET['desc'];
$type = $_GET['s1'];
$country = $_GET['countries'];
$emailopt = $_GET['s3'];
?>
the checker function:
function checker(){
if(isgood && isgood1 && isgood2 && isgood3 && isgood4 && isgood5 && isgood6)
{
return true;
}
else{
document.getElementById('subb').style.visibility="visible";
document.getElementById('subb').innerHTML = "You must fully complete the form.";
return false;
}
where the "isgoods" where just quick flags I made for validations, which was all working properly.
Your form's method is POST so you should use $_POST instead of $_GET in your PHP script.
Also you should fix up your HTML so it's valid, you need to quote the method attribute properly:
<form name="formname" id="formname" action="database.php" method="post" onsubmit="return checker()">
Well, I feel stupid. The problem was that I didn't give my HTML elements names, but rather just IDs. I was so used to using ajax and submitting by just getting the value with javascript via the ID that I forgot about names O.o
You are submitting your form with method="POST", so in your PHP you need to read the POST values:
$username = $_POST['un'];
...
Had you submitted your form with method="GET", your PHP code would work. Read about the difference here.

Categories