I have the following two script files (i.e., formtest.html and calc.php).
When I do the server side validation on calc.php, how do I pass the error message (i.e.
$err_msg back to the formtest.html?
Thank you
<html>
<head>
<title>Form Test</title>
</head>
<body>
<form method="post" action="calc.php">
<pre>
Loan Amount <input type="text" name="principle" />
<input type="submit" />
</pre>
</form>
</body>
</html>
.
// calc.php
$err_msg = '';
if ( !empty(isset($_POST['principle'])) )
{
// process the form and save to DB
} else {
$err_msg .= 'Loan Amount is empty!';
}
?>
You will either need to use a Server Side Include to bring in the PHP output into the HTML file (if it needs to remain an HTML file), or (a better solution) would be to include it all in one file like so:
(calc.php)
<?php
$err_msg = '';
if (isset($_POST['principle']) && !empty($_POST['principle']) )
{
// process the form and save to DB
} else {
$err_msg .= 'Loan Amount is empty!';
}
?>
<html>
<head>
<title>Form Test</title>
<script type="text/javascript">
<!--
var errMsg = '<?php echo $err_msg; ?>';
// Do something with javascript here.
-->
</script>
</head>
<body>
<div class="error">
<?php
// Or echo it inline with your HTML.
echo $err_msg;
?>
</div>
<form method="post" action="calc.php">
<pre>
Loan Amount <input type="text" name="principle" />
<input type="submit" />
</pre>
</form>
</body>
</html>
Not sure if that's valid as I wrote it off the top of my head. But that's the gist. Hope that made sense. ;)
**Changed code to reflect your comment.*
Related
I have 3 PHP files , the first one contain fields to compile which mean in html a form. the second , the code that took the fields from the first file and register them inside a folder .txt with a title=the date and time , the third file confirm the registration: i did the 3 files they work : but i would like to reload the fields page, in case where I click on the button and one or more of the fields is empty, with a comment near the field empty :
the first file form.php is:
I put the code only with one field to don't disturb more :`
<!doctype html>
<html lang="it">
<head>
<meta charset="utf-8">
<title>Titre de la page</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
}
<form action="POST.PHP" method="POST">
<input type="text" name="name" placeholder="name" value="name">
<button type="button">Click Me!</button>
</form>
</body>
</html>
the second file POST.php contain :
<?php
$nameErr= "";
$name = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Missing";
} else {
$name = $_POST["name"];
$filename="file/". date("Y-m-d_H_m_s") . "_" . uniqid() . ".txt" ;
$fp = fopen( $filename, "w" );
fwrite($fp, $name);
fclose($fp);
include 'registred.php';
}
}
?>
and the third file registred.php contain :
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<title>Titre de la page</title>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<h2>completed registration</h2>
<h3>wish to see you soon !!</h3>
<ul>
<li >name:<?=htmlspecialchars($name)?></li>
</ul>
</body>
</html>
This is not the best way to do that but its good enough to give you a idea about how u r gonna manage this.
<?php session_start();?>
<form action="post.php" method="post">
<input type="text" name="txtName">
<?php
if(isset($_SESSION['mising_data'])){
echo $_SESSION['mising_data'];
}
?>
<input type="submit" name="btnSubmit">
</form>
now in post.php file
<?php
session_start();
if (isset($_POST['btnSubmit'])) {
if (empty($_POST['txtName'])) {
$_SESSION['mising_data'] = 'missing Data';
header('Location: form.php');
}
}
?>
to handle this professionally u should use jquery ajax() method
I tried to execute the following html code:
<html>
<head>
<title>Listing 9.1 A simple HTML form</title>
</head>
<body>
<form action="listing.php" method="POST">
<p><strong>Name:</strong><br>
<input type="text" name="user"></p>
<p><strong>Address:</strong><br>
<textarea name="address" rows="5" cols="40"></textarea></p>
<p><input type="submit" value="send"></p>
</form>
</body>
</html>
And this is the code of the associated php file (listing.php):
<html>
<head>
<title>Listing Reading input from a form </title>
</head>
<body>
Welcome <?php echo $_POST["user"]; ?><br>
Your email address is: <?php echo $_POST["address"]; ?>
</body>
</html>
I was able to get the form and enter values as shown below:
Form Input
But, when I clicked 'Send Message', it displays only:
Welcome
Your email address is:
Without the values that I entered through the form.
When I tried to run the php file directly from the local host (http://localhost/listing.php), I received these error messages:
Welcome
Notice: Undefined index: user in C:\xampp\htdocs\listing.php on line 7
Your email address is:
Notice: Undefined index: address in C:\xampp\htdocs\listing.php on line 8
I even modified the php code as follows, but still got the same output:
<html>
<head>
<title>Listing Reading input from a form </title>
</head>
<body>
Welcome <?php
if(isset($_POST['submit'];)) {
session_start();
$user = $_POST['user'];
echo "$text";}else {echo 'Could not load text!';}?><br>
Your email address is: <?php echo $_POST["address"]; ?>
</body>
</html>
I would really appreciate it if you could give some advice to make it work.
Thanks
if(isset($_POST['submit'];)) should be changed,so you check if address and user is isset. Furthermore you normally don't want ; in your if statements.
Here i have a optimized version for you. the !empty is added so we also check if the inputs are not empty.
if (isset($_POST["name"] && isset($_POST["address"])) {
if (!empty($_POST["name"] && !empty($_POST["address"]) {
// execute code as u would
}
}
Notice: Undefined index: address in C:\xampp\htdocs\listing.php on line 8
This is caused by the use of the ';' in the if condition.
Remove that and you should be good. for now.
Try this code:
<html>
<head>
<title>Listing Reading input from a form </title>
</head>
<body>
Welcome <?php
if(isset($_POST['submit']))
{
session_start();
$user = $_POST['user'];
echo $user;
echo "<br><br>Your Email Address is: ".$_POST['address'];
}
else
{
echo 'Could not load text!';
}
?>
<br>
<form action="" method="POST">
<p><strong>Name:</strong><br>
<input type="text" name="user"></p>
<p><strong>Address:</strong><br>
<textarea name="address" rows="5" cols="40"></textarea></p>
<p><input type="submit" value="send" name="submit"></p>
</form>
</body>
</html>
In your second code block $text isn't defined anywhere. Do you mean to have $user?
<html>
<head>
<title>Listing Reading input from a form</title>
</head>
<body>
Welcome
<?php
if(isset($_POST['submit'])) {
session_start();
echo isset($_POST['user']) ? $_POST['user'] : "User";
} else {
echo "User";
}
?>
<br>
Your email address is:
<?php
echo isset($_POST["address"]) ? $_POST["address"] : "Address"
?>
</body>
</html>
Try this and let me know:
<?php
session_start();
if(isset($_POST['submit'])) {
$user = $_POST['user'];
echo "Welcome ".$user;
echo "<br>";
echo "Your email address is: ".$_POST["address"];
}else {
// you may get rid of this block if you like
echo 'Could not load text!';
}
?>
<html>
<head>
<title>Listing 9.1 A simple HTML form</title>
</head>
<body>
<form action="" method="POST">
<p><strong>Name:</strong><br>
<input type="text" name="user"></p>
<p><strong>Address:</strong><br>
<textarea name="address" rows="5" cols="40"></textarea></p>
<p><input type="submit" name='submit' value="send"></p>
</form>
</body>
</html>
So I want to replace the form submission with a thank you message after you submit, I need the PHP because this will eventually deal with databases in that php, however right now... The only way it works, is that is Type in a name, press submit. It goes back to a blank form, enter nothing (nothing in address) and submit again and it works...
right now the only way i could think of making it work would be some dummy checkbox where when checked value changes the post is sent. However i don't think that will pass with my groupmates
wondering how i can make it only have to submit once.
Index.PHP
<!DOCTYPE HTML>
<html>
<head>
<?php include_once "thankyou.php"; ?>
<script type="text/javascript" src="jquery-3.1.0.js"></script>
<script type="text/javascript">
$("document").ready(function() {
$("#ContactUs_Submit").click(function(evt) {
<?php $inputName = $_POST["ContactUs_Name"]; ?>
$("#ContactUs_CommentsDiv").replaceWith("<?php
thankyou($inputName); ?>");
return false;
});
});
</script>
</head>
<body>
<div id="ContactUs_CommentsDiv">
<form method="post">
<!-- WITH JQUERY USE SINGLE URL, WITH PAGES-->
<label for="ContactUs_Name">Name: </label>
<input type="text" name="ContactUs_Name" id="ContactUs_Name" />
<br/>
<Label for="ContactUs_Email">Email: </Label>
<input type="email" name="ContactUs_Email" id="ContactUs_Email" />
<br/>
<input id="ContactUs_Submit" type="submit">
</form>
</div>
</body>
</html>
thankyou.php
<?php
function thankyou($name) {
echo "<p> Thank you for your input ";
//if ($_POST["ContactUs_Name"] != "") {
// echo " " . $_POST["ContactUs_Name"];
// }
if ($name != ""){
echo $name;
}
echo "!";
}
?>
Can you not just use AJAX to do this?
The website generates the random number from 1 to 100 when accessing the first page(page1.php). And the user will guess the number.
The first page contains
- a text box for accepting a
number from the user, and a submit button.
The second page(page2.php) will be returned to the user if the guess number is too high or too low. And the page shows a message telling the user "Too High" or "Too Low". The page also contains
a button(retry button) that allows the user to go back to the first page(page1.php) to re-enter a new number
a button that allows the user to quit the game.
The third page(page3.php) is returned to the user if the guess is correct. The page displays "Correct", the random number, and the count of tries.
And I have this index.php which is heart for all the pages. And here is the code.
index.php
<?php
$name = '';
$inputnumber = '';
$random = 33; //this is just an assumption to keep it simple
$message = '';
$guesscount = '';
if (isset($_POST['action'])) {
$action = $_POST['action'];
}
if ($action === 'guess') {
$guesscount = $_POST['$guesscount'];
$inputnumber = $_POST['$inputnumber'];
if ($inputnumber == $random) {
$message = "Correct!";
include 'page3.php';
}
if ($inputnumber > $random) {
$message = "Too High";
include 'page2.php';
}
if ($inputnumber < $random) {
$message = "Too Low";
include 'page2.php';
}
}
if ($action === 'retry') {
include 'page1.php';
}
page1.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Number Guess</title>
</head>
<body>
<h1>Number Guess</h1>
<form name="myForm" action="index.php" method="post" >
Number Guess: <input type="text" name="$inputnumber" value="<?php if(isset($inputnumber)==1){
echo $inputnumber;}else echo ""; ?>" /><br>
<input type="submit" name="action" value="guess" />
<hr>
Guess Count: <?php echo $guesscount; ?>
</form>
</body>
</html>
page2.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Number Guess</title>
</head>
<body>
<h1>Number Guess</h1>
<form name="myForm" action="index.php" method="post" >
Message: <?php echo $message; ?>
<input type="hidden" name="$guesscount" value="<?php echo $guesscount;?>"/><br>
<input type="submit" name="action" value="retry" />
<hr>
Guess Count: <?php echo $guesscount;?>
</form>
</body>
</html>
page3.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Number Guess</title>
</head>
<body>
<h1>Number Guess</h1>
<form name="myForm" action="index.php" method="post" >
Message: <?php echo $message; ?>
Number of Tries: <?php echo $guesscount; ?>
<input type="submit" name="action" value="ok" />
</form>
</body>
</html>
page1.php is the page to load first.
Challenge I have faced is, I couldn't keep the $guesscount stable always. It keeps resetting on me. I have tried session but couldn't resolve it.Please help resolving it.
Thanks in advance.
I don't know why but my gut feeling tells me that the reason why the session is not working for you on other pages is because you do not initiate it ??
So what you have to do is:
index.php
<?php
session_start();
$_SESSION['myVariable'] = 'myVariable';
?>
page1.php
<?php
session_start();
$mySessionVar = $_SESSION['myVariable'];
var_dump($mySessionVar); // <- this should print myVariable
?>
You may get an error saying that $_SESSION is null or not set and to prevent that you can just enclose $_SESSION inside and isset method
if(isset($_SESSION['myVariable']) && $_SESSION['myVariable'] != null) {
$mySessionVar = $_SESSION['myVariable'[;
}
I'm having difficulty figuring out why my PHP form is processing on process.php but not returning to the form page with the appropriate $messages. Am I missing a line of code? I wrote this all up myself and it's the first time.
Here is my html:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test Contact Form - jQuery</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body>
<h3>Contact Us</h3>
<?php echo $contact_message; ?>
<form id="myForm" method="post" action="process.php">
<input name="name" type="text" value="<?php echo $_POST[name]; ?>" placeholder="Name" required/>
<br>
<input name="email" type="email" value="<?php echo $_POST[email]; ?>" placeholder="you#yourmail.com" required/>
<br>
<textarea name="message" class="message" placeholder="We can answer your questions." required>
<?php echo $_POST[message]; ?>
</textarea>
<br>
<button type="submit" name="submit" class="btn send">
<img src="img/send.png">
</button>
<br>
<?php echo $contact_success_message; ?>
</form>
<!--close contact form-->
</body>
</html>
And here is my process.php
<?php
//checks for valid email
function is_valid_email($email) {
$result = true;
$pattern = '/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\#([a-z0-9])(([a-z0-9-])*([a-z0-9]))+(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i';
if(!preg_match($pattern, $email)) {
$result = false;
}
return $result;
}
//when send is pressed, validate fields
if(isset($_POST['submit'])) {
$valid = true;
$contact_message = '';
if ( $_POST['name'] == "" ) {
$contact_message .= "You forgot to tell us your name. ";
$valid = false;
}
if ( !is_valid_email($_POST['email']) ) {
$contact_message .= "A valid email is required, don't worry we don't share it with anyone. ";
$valid = false;
}
if ( $_POST['message'] == "" ) {
$contact_message .= "What did you want to ask us? ";
$valid = false;
}
//if everything checks out, send the message!
if ( $valid == true ) {
$safe_email = str_replace("\r\n","",$_POST[email]);
$mail = "From: $_POST[name]\n";
$mail .= "Email: $_POST[email]\n";
$mail .= "$_POST[message]\n";
mail('ME#MYEMAIL.COM','New Contact from RN+',$mail,"From: $safe_email\r\n");
$contact_success_message = 'Brilliant I say! We will be in contact with you shortly.';
//clear form when submission is successful
unset($_POST);
}
}
?>
I could have sworn that I've used this before but this time it's not returning to the contact page.
It looks like you meant to use the code like this:
form.php
<?php include 'process.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test Contact Form - jQuery</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body>
<h3>Contact Us</h3>
<?php echo $contact_message; ?>
<form id="myForm" method="post" action="process.php">
<input name="name" type="text" value="<?php echo $_POST[name]; ?>" placeholder="Name" required/><br>
<input name="email" type="email" value="<?php echo $_POST[email]; ?>" placeholder="you#yourmail.com" required/><br>
<textarea name="message" class="message" placeholder="We can answer your questions." required><?php echo $_POST[message]; ?></textarea><br>
<button type="submit" name="submit" class="btn send"><img src="img/se
__
formnd.png"></button><br>
<?php echo $contact_success_message; ?>
</form><!--close contact form-->
</body>
</html>
The form processor will set the appropriate variables you are outputting in your HTML code. Since process.php checks if the method is POST, you don't have to do that in the form page.
If you want process.php to redirect back to your form, you need to add a PHP header code like: header('Location: http://www.example.com/form.php');
If you want to carry through any data back to the original page, include it in the URL as a GET variable: header('Location: http://www.example.com/form.php?message='.$messagetext); You can then retrieve this on your form page through use of GET: echo $contact_success_message = $_GET['message'];
Do not forget to exit(); or die(); after your redirect!
If you don't have any reason for excluding a single PHP page, you could merge the two (form and process) into one php page.
<?php
//checks for valid email function
...
if(isset($_POST['submit'])) {
...
}
?>
...your HTML goes here...
This will display just the form if no data has been submitted, and if the form has been submitted will "reload" the page, perform the action, and display the appropriate message. Change the form action to action="" so the file will post to itself.
I would recommend using jQuery validation. It is easier and will help with any issues you might have in returning the message.
http://docs.jquery.com/Plugins/Validation
Something like this...
$("#myForm").validate({
rules: {
name: { required: true; }
},
messages: {
name: "You forgot to tell us your name.",
}
});
You can do this for email fields and for your whole form. You can find plenty of examples online.
Just include your other fields. If you do it this way the validation is client side and the form will process and then you forward to a thank you for contacting us page.