PHP form request with javascript form validation - javascript

So i have a javascript that performs a simple form validation on
<form method="get" name="formPG" onsubmit="return (validateForm());" action="filter.php">
<p>Noun <input id="iNoun" name="fNoun" type="text" /></p>
<p><br />
Pronoun <input id="iPronoun" name="fPronoun" type="text" /></p>
<p><br />
Verb <input id="iVerb" name="fVerb" type="text" /></p>
<p><br />
Adverb <input id="iAdverb" name="fAdverb" type="text" /></p>
<p><br />
Adjective <input id="iAdjective" name="fAdjective" type="text" /></p>
<p><br />
Silly Word <input id="iSillyWord" name="fSillyWord" type="text" /></p>
<p><br />
Magic Spell <input id="iMagic" name="fMagic" type="text" /></p>
<p><br />
<input type="submit" value="submit" /></p>
</form>
The javascript says "hey this is filled in" or "hey this isn't filled in, please fill this in".
Now, I have a PHP file that collects the information from the HTML tags
<?php
require "start.php"
?>
<div class="work"><</div>
<?php
if(!empty($_GET['fNoun']) && !empty($_GET['fPronoun']) && !empty($_GET['fVerb']) && !empty($_GET['fAdverb']) && !empty($_GET['fAdjective']) && !empty($_GET['fSillyWord']) && !empty($_GET['fMagic']))
{
$noun = filter_input(INPUT_GET, 'fNoun', FILTER_SANITIZE_STRING);
$pronoun = filter_input(INPUT_GET, 'fPronoun', FILTER_SANITIZE_STRING);
$verb = filter_input(INPUT_GET, 'fVerb', FILTER_SANITIZE_STRING);
$adverb = filter_input(INPUT_GET, 'fAdverb', FILTER_SANITIZE_STRING);
$adjective = filter_input(INPUT_GET, 'fAdjective', FILTER_SANITIZE_STRING);
$sillyword = filter_input(INPUT_GET, 'fSillyWord', FILTER_SANITIZE_STRING);
$magic = filter_input(INPUT_GET, 'fMagic', FILTER_SANITIZE_STRING);
echo "There was once a $adjective magician who roamed the wild terrains of $adverb <br>The magician $noun cast the mighty spell $magic around the $sillyword <br>$pronoun knew there was only one way to win the war - $verb";
}
else
{
echo "parameters not provided."
}
?>
<?php
require "end.php"
?>
The problem I am running into is it collects the information (which you can see it in the URL) however, it doesn't echo out the information to the screen.
Could it be a weird interaction with PHP and JavaScript?

Here is one option, you will want to first check what filter_input returns and then you can assign that to a variable and display it, below is a simple example, derived from what w3schools provides here: https://www.w3schools.com/php/showphp.asp?filename=demo_func_filter_input . The example below validates an email from a form and if filter input does not return false it will print a message saying 'This email: is a valid Email'
Example:
<!DOCTYPE html>
<html>
<body>
<form method="get" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
E-mail: <input type="text" name="email">
<input type="submit" name="submit" value="Submit">
</form>
<?php
if (isset($_GET["email"])) {
if (!filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL) === false) {
$email = filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL);
echo("This email: ".$email." is a valid Email");
} else {
echo("Email is not valid");
}
}
?>
</body>
</html>
Hope this helps.

Related

AJAX form with priority values

I want to create form with priority values, first check vlaue of recaptcha if is correct (not spammer) then do process for example:
if(isset($_POST['g-recaptcha-response']))
{
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha)
{
echo "enter captcha";
}
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=*******&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
if($response.success==TRUE){
$name = $_POST['name'];
if($name == "hello"){
echo 'correct';
}
else {
echo 'incorrect';
}
}
if($response.success==false)
{
die("spammer!");
}
and HTML code like:
<form id="form" method="POST" action="">
<input id="name" name="name" type="text"/>
<div class="g-recaptcha-response" data-sitekey="******"></div>
<input id="button" type="submit" value="send" />
</form>
<div id="formresult"></div>
<div id="formresult"></div> is for ajax answer
I wrote some script code but not worked and I prefer ask without paste that code in here. how could I do that?

How to give action on php pages

I have made two pages. I have used php form validation in my first page, i.e., form.php and I have to give action on second page i.e., data_ins.php. Please let me know how will it possible with my coding.
Here are my pages:
form.php
<?php $fnameErr = $lnameErr = "";
$fname = $lname= ""; if($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST['fname']))
{
$fnameErr = "First Name is required";
}
else
{
$fname= formVal($_POST['fname']);
}
if(empty($_POST['lname']))
{
$lnameErr = "Last Name is required";
}
else
{
$lname= formVal($_POST['lname']);
} }
function formVal($data)
{
$data = trim($data);
$data = stripcslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?> <!DOCTYPE html> <html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
First Name:
<input type="text" name="fname"> <span style="color:red;"><?php echo $fnameErr ?></span> <br>
Last Name:
<input type="text" name="lname"> <span style="color:red;"><?php echo $lnameErr ?></span> <br>
<input type="submit" name="submit">
</form>
</body> </html>
data_ins.php
<?php $conn = mysqli_connect("localhost","root","","test_db");
$sql = "insert into records (FirstName, LastName) values ('$fname', $lname)";
if($result=mysqli_query($conn, $sql))
{
echo "Data Inserted Successfull";
}
else
{
echo "Invalid";
}
mysqli_error($conn); ?>
Personally, I think you may of made it harder than you needed to.
Here is what I'd do with the PHP side:
if (isset($_POST['submit']))
{
if (!empty($_POST['fname']))
{
if (!empty($_POST['lname']))
{
// Add Database insert code here..
} else {
echo "Last name is required";
}
} else {
echo "First name is required";
}
}
As for the form, you don't need to add the PHP self (just add the method) like so:
<form method="POST" action="">
First Name: <input type="text" name="fname"><br>
Last Name: <input type="text" name="lname"><br>
<input type="submit" name="submit">
</form>
Hope this helps more so than your initial idea of doing it.
PLEASE NOTE: I haven't added the $data trim etc in but you'd add these in firstly where // do code note is.
1.change your form like this
`<form method="POST" action="location of your data_ins.php">`
2.in your data_ins.php must have database config code or include it.
3.get your all form value in data_ins.php pass to insert query
<form method="POST" action="">
First Name: <input type="text" name="fname"><br>
Last Name: <input type="text" name="lname"><br>
<input type="submit" name="submit">
</form>
Besides your code, your method (as question is not about it).
To execute other .php file you can use PHP statements:
require
include
include_once
In your case require should be the one to use, like: require 'data_ins.php'; after validation.

Display custom error message in login

I want to implement a simple login with PHP. But, also I want to customize the error message when the login is incorrect, for example display a error message in red color.
Login.php
<form id="frmlogin" name="frmlogin" method="POST" action="validarUsuario.php">
<p><input type="text" name="usuario" id="usuario" class="required" maxlength="50" placeholder="Nombre Usuario"></p>
<p><input type="password" name="password" id="password" class="required" maxlength="50" placeholder="Password"></p>
<p id=error> </p>
<p class="submit"><input type="submit" name="commit" value="Login"></p>
</form>
validarUsuario.php
<?php
include("connection.php");
conectar_bd();
$usr = $_POST['usuario'];
$pw = md5($_POST['password']);
$sql = "SELECT usr FROM Client WHERE usr = '$usr'AND password ='$pw'";
$result = mysql_query($sql, $con);
if ($fila = mysql_fetch_array($result)) {
header('Location: menuclient.php');
} else {
/* How customize my message error */
}
?>
In the Login.php file, when the username or password are not correct, i want to display, for example, in id=error : "Login Incorrect" in red.
I dont know if I can do it with php.
Thanks for your help.
You can use session. Try following way.
Login.php
<?php
session_start();
if($_SESSON['error']): ?>
<span>Error : <?php echo $_SESSION['errorMsg']; ?></span>
<?php endif; ?>
<form id="frmlogin" name="frmlogin" method="POST" action="validarUsuario.php">
<p><input type="text" name="usuario" id="usuario" class="required" maxlength="50" placeholder="Nombre Usuario"></p>
<p><input type="password" name="password" id="password" class="required" maxlength="50" placeholder="Password"></p>
<p id=error> </p>
<p class="submit"><input type="submit" name="commit" value="Login"></p>
</form>
validarUsuario.php
<?php
session_start();
include("connection.php");
conectar_bd();
$usr = $_POST['usuario'];
$pw = md5($_POST['password']);
$sql = "SELECT usr FROM Client WHERE usr = '$usr'AND password ='$pw'";
$result=mysql_query($sql,$con);
if( $fila=mysql_fetch_array($result) )
{
header('Location: menuclient.php');
}
else {
$_SESSION['errorMsg'] = "Wrong username or Password";
$_SESSION['error'] = true;
header('Location: Login.php');
}
?>

Run PHP before HTML with action. Getresponse

I'm trying to integrating a PHP function to add the database into my file for tracing out purpose.
Here's my HTML code :-
<div id="" class="wf-formTpl">
<form accept-charset="utf-8" style="margin-top:;" action="https://app.getresponse.com/add_contact_webform.html?u=fgWk" method="post">
<input class="wf-input wf-req wf-valid__email" type="text" name="email"
data-placeholder="yes" value="Enter Your Email Here" onfocus=" if (this.value == 'Enter Your Email Here') { this.value = ''; }" onblur="if (this.value == '') { this.value='Enter Your Email Here';} " style="margin-top:;"></input>
<br />
<input type="submit" class="wf-button" name="submit" value="" style="display: inline !important; margin-top:-10px !important;"></input>
<input type="hidden" name="webform_id" value="6724404" />
</form>
</div>
<script type="text/javascript" src="http://app.getresponse.com/view_webform.js?wid=6724404&mg_param1=1&u=fgWk"></script>
Here's the PHP code :
<?php
$time = $_POST['email'];
if(isset($_POST['submit'])){
echo '<script type="text/javascript">alert("Done");</script>';
$myFile = "user.html";
$fh = fopen($myFile, 'w') or die("error");
$stringData = 'Notification'.$time;
fwrite($fh, $stringData);
};
?>
The PHP function doesn't go through , a.k.a the javascript function doesn't pops up.
I need a favor on how to make this happen :(
The function runs the HTML but not the PHP .
Thanks in advance.

Can I remove "&& isset" in a php form

I have got the following form to work using PHP and JavaScript to validate...
The problem is, each time I want to update the inputs in the form I need to also update the && isset and $input = $_REQUEST['input name']; in the PHP! Are these important? there is no way to make the whole process easier?! please advise
PHP:
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
ob_start();
if(isset($_REQUEST['name'])
&& isset($_REQUEST['email'])
&& isset($_REQUEST['message'])
&& isset($_REQUEST['number'])
&& isset($_REQUEST['date'])
&& isset($_REQUEST['select'])
&& isset($_REQUEST['radio'])
&& isset($_REQUEST['checkbox'])
&& isset($_REQUEST['token'])){
if($_SESSION['token'] != $_POST['token']){
$response = "0";
} else {
$_SESSION['token'] = "";
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
$number = $_REQUEST['number'];
$date = $_REQUEST['date'];
$select = $_REQUEST['select'];
$radio = $_REQUEST['radio'];
$checkbox = $_REQUEST['checkbox'];
$to = "";
$subject = "New Message From: $name";
$message = "Name: $name<br/>
number: $number<br/>
date: $date<br/>
select: $select<br/>
radio: $radio<br/>
checkbox: $checkbox<br/>
Email: $email<br/>
Message: $message";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= 'From: '.$email . "\r\n";
$mailed = (mail($to, $subject, $message, $headers));
if( isset($_REQUEST['ajax']))$response = ($mailed) ? "1" :
"0"; else $response = ($mailed) ? "<h2>Success!</h2>" :
"<h2>Error! There was a problem with sending.</h2>";
echo $response;
}
} else {
echo "Form data error!";
}
ob_flush();
die();
}
?>
HTML Form:
<?php
$token = md5(uniqid(rand(), TRUE));
$_SESSION['token'] = $token;
?>
<!--Contact Form-->
<form id="contactForm" name="contactForm" action="contact.php" method="post">
<input name="token" type="hidden" value="<?php echo $token; ?>">
<input name="ajax" type="hidden" value="1">
<div class="name">
<p>Your Name</p>
<input name="name" class="required" autocomplete="off">
</div>
<div class="email-address">
<p>Email Address</p>
<input name="email" class="required email" autocomplete="off">
</div>
<div class="message">
<p>Message</p>
<textarea name="message" rows="5" class="required min3"></textarea>
</div>
<div class="number">
<p>Phone Number</p>
<input name="number" class="number" autocomplete="off">
</div>
<div class="date">
<p>Date <small>(dd/mm/yyyy)</small></p>
<input name="date" class="required date calendar" autocomplete="off">
</div>
<div class="dropdown">
<select name="select" class="required">
<option value="">Select</option>
<option value="DropdownA">DropdownA</option>
<option value="DropdownB">DropdownB</option>
</select>
</div>
<div class="radio">
<p>Radios:</p>
<label><input name="radio" type="radio" value="male" class="required">Male</label>
<label><input name="radio" type="radio" value="female" class="required">Female</label>
</div>
<div class="checkbox">
<p>Checkboxs:</p>
<label><input name="checkbox" type="checkbox" value="OptionA" class="required">Option A</label>
<label><input name="checkbox" type="checkbox" value="OptionB" class="required">Option B</label>
</div>
<div>
<p></p>
<input name="" class="required number spamcheck">
</div>
<button id="submit" type="submit">Send</button>
</form>
You do need to check if variables are set, before using them. Otherwise your script will raise errors for undefined variables. E.g. You each time will try to check if $_SESSION['token'] != $_POST['token'] but it will give you errors, because there's no form submitted (or however the request is sent) with token name, that's why you do need to check it before that.
Anyway, for multiple isset() you can use a comma separator
if(isset($var, $var2, $var3...))
instead of
if(isset($var) && isset($var2)...))
Also,, if you session token is not initialized too (completely new request to the page), and no request is send to it, your if() statement will return false, thus triggering the mail() function. So, in you particular case it's more than necessary to have a check before using them in mail form.
Yes. They are important. Lots of ways to make the process easier though. You might want to look at a simple framework like Symfony (the forms component can be used independently of the whole framework).
Be aware that you'll probably get a massive amount of spam with that form. Add a captcha like reCaptcha.
Yes, the validation is important but you can simplify your code. I would use an array to define the required fields. It's easy to maintain and much less code.
$requiredFields = array('name', 'email', 'message', 'number');
$valid = true;
foreach ($requiredFields as $field) {
if (!isset($_REQUEST[$field])) {
$valid = false;
break;
}
}
if ($valid) {
// Do the stuff
} else {
echo "Form data error!";
}
If you want to check if the current field actually contains something add empty() to the condition:
if (!isset($_REQUEST[$field]) || empty($_REQUEST[$field])) {
I think the second part where you assign the post values to separate variables is actually unnecessary in this case.

Categories

Resources