PHP form not processing in process.php - php

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.

Related

PHP Forms With JQuery Requiring to press submit twice

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?

Display PHP POST results after a form submit, then reload same blank form when page "Refresh" clicked

After over 6 hours of searching here and other forums/blogs, still found no operational method to do this, all on same page; so I remain confident this has not been asked in exact same way: Enter some data to a form, submit, show results... then if user clicks "Refresh", show the original blank form and not show a browser message about "You are resending data, etc. etc." Here is the base code, it functions as expected, just desire to have starting blank form show after clicking browser "Refresh". I have attempted both PRG and Sessions methods without success.
<!DOCTYPE html >
<head>
<title>Refresher test</title>
</head>
<body>
<br/><br/><h2>What Me Refresh</h2>
<?php
//If form not submitted, display form.
if (!isset($_POST['submit'])||(($_POST['text']) == "")){
?>
<p><h3>Enter text in the box then select "Go":</h3></p>
<form method="post" action="RfrshTst.php" >
<textarea rows="5" cols="50" name="text" >
</textarea>
<input type="submit" name="submit" value="Go" />
</form>
<?php
//If form submitted, process input.
} else {
//Retrieve show string from form submission.
$txt = $_POST['text'];
echo "The text you entered was : $txt";
} ?>
</body>
</html>
This solution uses the session.
First stores in the session the post field if it exists and then redirects to the same page.
If it finds the field in the session, it gets it and remove it from session and show it on the page.
<?php
$txt = "";
session_start();
if (isset($_POST['submit']) && (($_POST['text']) != "")) {
$_SESSION['text'] = $_POST['text'];
header("Location: ". $_SERVER['REQUEST_URI']);
exit;
} else {
if(isset($_SESSION['text'])) {
//Retrieve show string from form submission.
$txt = $_SESSION['text'];
unset($_SESSION['text']);
}
}
?>
<!DOCTYPE html >
<head>
<title>Refresher test</title>
</head>
<body>
<br/><br/><h2>What Me Refresh</h2>
<?php
if($txt != "") {
echo "The text you entered was : $txt";
} else {
?>
<p><h3>Enter text in the box then select "Go":</h3></p>
<form method="post">
<textarea rows="5" cols="50" name="text" >
</textarea>
<input type="submit" name="submit" value="Go" />
</form>
<?php } ?>
</body>
</html>
Try this code. You need to use JS to refresh without POSTing again.
<!DOCTYPE html >
<head>
<title>Refresher test</title>
</head>
<body>
<br/><br/><h2>What Me Refresh</h2>
<?php
//If form not submitted, display form.
if (!isset($_POST['submit'])||(($_POST['text']) == "")){
?>
<p><h3>Enter text in the box then select "Go":</h3></p>
<form method="post" action="RfrshTst.php" >
<textarea rows="5" cols="50" name="text" >
</textarea>
<input type="submit" name="submit" value="Go" />
</form>
<?php
//If form submitted, process input.
} else {
//Retrieve show string from form submission.
$txt = $_POST['text'];
echo "The text you entered was : $txt";
?>
<button onclick="location = location.href">Refresh</button>
<?php
} ?>
</body>
</html>
even Wiki has an article for you. I wonder how couldn't you find it?
you can do it with php:
<?php
// handle $_POST here
header('Location:yourscript.php');
die();
?>
JS:
window.location = window.location.href;
or Post/Redirect/Get which is the best I think
You can't just delete the $_POST data from the server. The browser alerts it because it is stored by the browser. If it resubmits the data then it will send it back to the server and repopulate $_POST
You can achieve this by setting a cookie / session variable, which tells you the form was already processed.
<?php session_start(); ?>
<!DOCTYPE html >
<head>
<title>Refresher test</title>
</head>
<body>
<br/><br/><h2>What Me Refresh</h2>
<?php
//If form not submitted, display form.
if (isset($_POST['submit']) && !isset($_SESSION['user'])){
//Retrieve show string from form submission.
$txt = $_POST['text'];
echo "The text you entered was : $txt";
$_SESSION['user'] = true;
//If form submitted, process input.
} else {
?>
<p><h3>Enter text in the box then select "Go":</h3></p>
<form method="post" action="" >
<textarea rows="5" cols="50" name="text" >
</textarea>
<input type="submit" name="submit" value="Go" />
</form>
<?php
} ?>
</body>
</html>
Dont forget to empty the action as you have mentioned in question(bold) All on same page
<form method="post" action="RfrshTst.php" >
^--Here^

PHP form validation, uses Javascript for error messages

OK so I have an email form on index.php. I am using mail_check.php to validate that both fields are filled in.
(there are more that is being validated, but not included as it is not the issue)
The main issue is that from the mail_check.php I want to be sent back to the index.php with a message in placed in the div id="mailrespond". I have chosen both PHP and Javascript to achieve this.
Index.php
<div id="mailrespond"></div>
<form method="post" action="mail_check.php">
<span>Name: <input type="text" name="name" maxlength="30" /></span><br />
<span>Email: <input type="text" name="email" maxlength="30" /></span><br />
<input type="submit" value="Sign Up" name="registration">
</form>
</div>
mail_check.php
if(isset($_POST['registration']))
$name = $_POST['name'];
$email = $_POST['email'];
if(empty($email) || empty($name)){
// if email and name are empty
//header ("location: index.php");
?>
<script language="javascript" type="text/javascript">
window.location.replace("index.php");
function msg() {
// creating elements are a safer method then innerHTML
dv = document.createElement('div'); // creates a Div element
dv.setAttribute('class', 'error_msg'); // adds error styling
txt = document.createTextNode('please enter your name and email '); // create the message
dv.appendChild(txt); // place the text node on the element
document.getElementById("mailrespond").appendChild(dv);
}
window.onload = msg;
</script>
<?php }
The code goes on, but My issue is that I am not getting the feed back messages. I am a little new to this all - if you can help that would be much appreciated! :)
<---- #downvoter please leave a reason! Thanks
Try this (and don't call a form field name, please since a form can have a name too)
Index.php
<!DOCTYPE html>
<html>
<head>
<title>Mail respond</title>
<script>
window.onload=function() {
document.getElementById("mailform").onsubmit=function(){
if (this.fullname.value=="" || this.email.value=="") {
alert("Please fill in name and email");
return false;
}
return true; // allow form submission
}
}
</script>
</head>
<body>
<div id="mailrespond"></div>
<form method="post" action="mail_check.php" id="mailform">
<span>Name: <input type="text" name="fullname" maxlength="30" /></span><br />
<span>Email: <input type="text" name="email" maxlength="30" /></span><br />
<input type="submit" value="Sign Up" name="registration">
</form>
</div>
</body>
</html>
mail_check.php
<?PHP
if(isset($_POST['registration']))
$name = $_POST['fullname'];
$email = $_POST['email'];
if(empty($email) || empty($name)){
// if email and name are empty - only seen if JavaScript is turned off
?>
<h3>You did not fill in name and email</h3>
<p>please wait to be redirected or click <a href='index.php'>here</a></p>;
<meta http-equiv="refresh" content="3; url=http://example.com/index.php" />
<script type="text/javascript">
window.onload=function() {
setTimeout(function() {
window.location.replace("index.php");
},3000);
}
</script>
<?php } ?>
You're redirecting to index.php in the msg function, so it does nothing else.
You should do it by pure PHP, set a component in $_SESSION, redirect by PHP to index.php and in the index.php check if the component exists.

Submit button not working?

I have this small test page trying to mess around and figure out PHP code, from what I understand, after filling the forms and hitting submit, something should happen. Depending on what you entered.
<!DOCTYPE html>
<html>
<head>
<title>PHP Testing Page</title>
</head>
<body>
<?php
echo "Testing Page, working great!\n";
$theDate = date("M-d-Y ");
echo "Today is " . $theDate;
$email1 = $_POST['email1'];
$email2 = $_POST['email2'];
function checkEmail()
{
$email1 = $_POST['email1'];
$email2 = $_POST['email2'];
echo $email1;
echo $email2;
if($email1==$email2)
{
echo "\nE-Mail Addresses match.";
}
else
{
echo "\nCheck to make sure your E-Mails match";
}
}
?>
<form name="checkingEmail" action="." method="post">
E-Mail: <input type="text" name="email1" value="E-Mail Here" />
<br />
Retype E-Mail: <input type="text" name="email2" value="Confirm E-Mail" />
<br />
<input type="button" value="Submit" onClick="checkEmail()">
</form>
</body>
</html>
After the forms are filled (via visiting page) and the Submit button is clicked, nothing happens. Can someone explain please?
********EDIT******FIXED**
Found a work around! No functions, works like a charm.
<!DOCTYPE html>
<html>
<head>
<title>PHP Testing Page</title>
</head>
<body>
<?php
echo "Testing Page, working great!\n";
$theDate = date("M-d-Y ");
echo "Today is " . $theDate;
?>
<form name="checkingEmail" action="test.php" method="post">
E-Mail: <input type="text" name="email1" value="E-Mail Here" />
<br />
Retype E-Mail: <input type="text" name="email2" value="Confirm E-Mail" />
<br />
<input type="submit" value="Submit">
</form>
<?php
$email1 = $_POST["email1"];
$email2 = $_POST["email2"];
if($email2==null)
{
/*I believe this just stops it from checking the rest of the conditions, that
way it won't echo anything until someones enters valid (non-null) input*/
$email2 = "notnull";
}
else if($email1==$email2)
{
echo "Good Job.";
}
else
{
echo "Failure to comply.";
}
?>
</body>
I have the check outside of a function, so I don't have to call it or anything like that. Also, with the first if statement, if $email2 is null (When they first load it) it will
simply change $email2 to "notnull" and stop checking statements because it found a valid
one. (Not 100%)
Where is your submit button ?
<input type="button" value="Submit" onClick="checkEmail()">
^
The type should be submit
As mentioned on this answer comments, you can't call a php function from javascript.
When you do it you'll call checkEmail from a javascript, which isn't defined.
So, you'll get the following error:
Uncaught ReferenceError: checkEmail is not defined
type should be submit;
If you change it to the submit and then run it, it should be fine. You should use submit type with Form elements.

How to pass the server side validation messages back to client?

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.*

Categories