How to stay on same page after form submission? - php

I have a simple PHP question.
I have a textbox where the user enters in their email and submit to be part of our mailing list. Now the textbox is on every page as it's part of our footer. The issue I am getting is that it keeps trying to relocate me to marketing-email.php (where the php that handles all of the form submission occurs'. I want the location to stay on the current page the user is on. I tried the code below with:
header("Location: $_SERVER['HTTP_REFERER']?mailingsent=1");
die;
But it still takes me to marketing-email.php. Plus it gives me a syntax error of unexpected EOF.
How can I get this to work so that after submission, it stays on current page with just a parameter added at the end?
Code below:
footer.php
<?php
$mailingsent=0;
if (isset($_GET['mailingsent'])) {
$_GET['mailingsent'];
}
?>
<html>
<body>
...
<section id="marketing-email">
<form class="marketing-email-form" method="post" action="https://test.com/marketing-email.php">
<div>
<label for="email"><b>Stay updated on any new courses and services we have to offer by joining our mailing list</b></label><br/>
<input type="email" id="market-email" name="market-email" required placeholder="Email"/>
<button type="submit" class="marketing-btn">Send</button>
</div>
</form>
</section>
<?
if (isset($_GET['mailingsent'])) {
echo ' <section id="mailing_list_email_sent" style="background-color:green !important;width:100%;">
<div class="container">
<div class="row">
<div class="col-md-12">
<p class="tagline-content">
Email successfully sent to our mailing list!
<span class="closemailinglistemailmsg"
style="color:white;
font-size:1.5em;
float:right;">×</span>
</p>
</div>
</div>
</div>
</section>';
}
?>
...
<script>
// Get the modal
var modal = document.getElementById("mailing_list_email_sent");
// Get the <span> element that closes the modal
var spanMailingList = document.getElementsByClassName("closemailinglistemailmsg")[0];
// When the user clicks on <span> (x), close the modal
spanMailingList.onclick = function() {
modal.style.display = "none";
}
</script>
marketing-email.php
<?php
$errors = '';
if(
empty($_POST['market-email']
))
{
$errors .= "\n Error: email is required";
}
$email_address = $_POST['market-email'];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
$errors .= "\n Error: Invalid email address";
}
if( empty($errors))
{
$email_body = "Request to join mailing list: $email_address";
$email_subject = "Mailing List Metis - $email_address";
mail("test#test.com",$email_subject,$email_body);
header("Location: $_SERVER['HTTP_REFERER']?mailingsent=1");
die;
}
?>

You can just make it as function and include it to the file for submission...
marketing-email.php
Eg: function submitHandleter($data){
And write all of your logic
}
In footer.php
about your form include(marketing-email.php);
And call the function
if(isset($_POST['market-email'])){
submitHandleter($_POST);
}
And keep the form action for the same page

Related

PHP Checkbox Values Not Saved During Error Check or Posting

The "newvar_" values for "029, 032 and 033" are not being remembered during error-checking, nor are they being posted when a corrected form is submitted.
The "name" field works correctly both on error checking and posting.
The form default for the all checkboxes is not selected.
The user should be able to select only the forms they wish. Their selection should post to the txt file along with their name.
The validation library am using can be found at: http://www.benjaminkeen.com/software/php_validation
Thanks in advance for your assistance.
<?php
// Eliminate server error notices except for parse errors
error_reporting(E_PARSE);
// Receiving variables
$errors = array(); // set the errors array to empty, by default
$fields = array(); // stores the field values
if (isset($_POST['submit']))
{
// Import the validation library
require("../include/validation.php");
$rules = array(); // stores the validation rules
// Rules specific to this form
$rules[] = "required,name,Please enter Your Name.";
$rules[] = "length<71,name,Your Name is too long.";
// Check the user's entries for errors based upon above rules
$errors = validate_fields($_POST, $rules);
// If there were errors, re-populate the form fields with user entries
if (!empty($errors))
{
$fields = $_POST;
}
// If there were no errors
else
{
// Redirect to a "thank you" page URL shown below
header("Location: thank-you.php");
}
}
// Count the errors. If none process the form data
if (count($errors) == 0) {
// Location of flat file database - absolute path
$datafile_01 = '/home/domain/public_html/Forms.txt';
// Strip-out the HTML tags
$_GET = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
// Write successfully submitted form data to flat file database
if ($_POST['submit']) {
$file = fopen($datafile_01, "a");
if (!$file) {
die("Can't write to database file");
}
// Set timezone to match delivery location
date_default_timezone_set('America/New_York');
$date = date('Y m-d g:i:s a');
// Select and code the fields being posted
$name = $_POST['name'];$name=($name);
//FORMS & SUPPLIES
// Standard Forms they requested
// Change the checkbox 'on' to something else (defined by $Newvar)
if($Form_F_029 == 'on') { $Newvar_029 = &$Form_F_029; $Newvar_029 = "X"; }
if($Form_F_032 == 'on') { $Newvar_032 = &$Form_F_032; $Newvar_032 = "X"; }
if($Form_F_033 == 'on') { $Newvar_033 = &$Form_F_033; $Newvar_033 = "X"; }
// Format the fields for the flat file
fwrite($file,
"Name:\t $name\n
REQUESTED FORMS AND SUPPLIES:\n
STANDARD FORMS ++++++++++++++++++++
Form F-029:\t $Newvar_029
Form F-032:\t $Newvar_032
Form F-033:\t $Newvar_033\n
=============================================================================== EOF =\n\n);"
fclose($file);
}
// Format and send email notice of successful submittal
if ($_POST['submit']) {
$sn_header = "From: Inquiries Database\n"
. "Reply-To: no_reply#domain.com\n";
$sn_subject = "Ordering Supplies Request";
$sn_email_to = "someone#domain.com";
$sn_message = "Please check the database for a recent submission.\n\n"
. "This is a post-only message.\n\n"
. "Do not reply.\n";
#mail($sn_email_to, $sn_subject ,$sn_message ,$sn_header ) ;
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Form Test</title>
<meta charset="utf-8" />
<meta name="viewport"
content="width=device-width, initial-scale=1" />
<?php //This CSS needed only for forms to style Modal ?>
<link rel="stylesheet"
href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"
media="screen" />
</head>
<body>
<!-- Wrapper -->
<div id="wrapper" class="divided">
<section class="wrapper style1 align-left">
<div class="inner">
<h2 class="color-1">Measuring & Ordering Supplies</h2>
<form action="<?=$_SERVER['PHP_SELF']?>" name="inquiry" method="post">
<div class="field">
<label style="margin:1rem 0 .25rem 0"><i class=" color-1 fa fa-star"></i> Your Name:</label>
<input type="text" name="name" id="name" value="<?=$fields['name']?>" />
</div>
<div class="field" style="padding-top:1rem">
<label style="font-size:110%; margin-bottom:0"><b class="color-1">Standard Forms</b>
<span style="font-weight:300; font-size:80%">Check box to order | Click name to download PDF</span><br />
</label>
</div>
<div class="field third first" style="padding-top:10px">
<input type="checkbox" id="Form_F_029" name="Form_F_029" <?php if($Form_F_029 == "on"){echo "CHECKED";}?> />
<label for="F_029">Form F 029
</label>
</div>
<div class="field third" style="padding-top:10px">
<input type="checkbox" id="Form_F_032" name="Form_F_032" <?php if($Form_F_032 == "on"){echo "CHECKED";}?> />
<label for="Form_F_032">Form F 032
</label>
</div>
<div class="field third" style="padding-top:10px">
<input type="checkbox" id="Form_F_033" name="Form_F_033" <?php if($Form_F_033 == "on"){echo "CHECKED";}?> />
<label for="Form_F_033">Form F 033
</label>
</div>
<ul class="actions" style="padding-top:30px">
<li><input type="submit" class="button small" name="submit" id="submit" value="Submit Request" /></li>
</ul>
</form>
</div>
<div id="error" title="Form Errors:">
<?php
// if $errors is not empty display them in the modal
if (!empty($errors))
{
echo "<div style=\"padding:15px 15px 0 15px\">";
echo "<ul style=\"margin-bottom:20px\">";
foreach ($errors as $error)
echo "<li style=\"font-size:15px; padding:5px\">$error</li>";
echo "</ul></div>";
}
?>
</div>
</section>
<!-- Footer -->
</div>
<!-- Scripts -->
<?php include $_SERVER["DOCUMENT_ROOT"] . "/assets/includes/php/javascripts-01.php"; ?>
<?php // Supporting scripts for Error Modal ?>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
<?php if( isset( $_POST["submit"] ) ){ ?>
$('#error').dialog({
height: 380,
width: 260,
modal: true,
resizable: false,
dialogClass: 'no-close error-dialog'
});
<?php } ?>
</script>
</body>
</html>
The values of $Form_F_029, _032, _033 are never set.
You copied the POST variables into $fields:
$fields = $_POST;
So this worked as intended:
<input type="text" name="name" id="name" value="<?=$fields['name']?>" />
But uses of $Form_F_0xx are treated as null, undefined or false depending on context:
<input type="checkbox" id="Form_F_029" name="Form_F_029" <?php if($Form_F_029 == "on"){echo "CHECKED";}?> />
You could fix this by setting
$Form_F_029 = $fields['Form_F_029'];
or
$Form_F_029 = $_POST['Form_F_029'];
etc.
For debugging problems like this it can help to include the values of variables and arrays in your output, for example in a comment or pre tag:
echo "<!-- 29= $Form_F_029, 32 = $Form_F_032 -->"; // DEBUGGING
echo "<pre>- 29= $Form_F_029, 32 = $Form_F_032 </pre>"; // DEBUGGING
Just remember to delete them or comment them out later.

Can't get rid of blank php page after submission form

Were searching for few hours answer on this but I'm completely stacked and brain freezes.
Have subscribe php form with bootstrap modal on successful submission. Everything works, emails passing through, modal showing just after one second or less blank page appear.
I guess that is loaded before form.php file is a separate file but is it there a way to stop loading blank page?
Here is Html code
<form action="form.php" method="post">
<div class="form-group label-floating">
<input name="email" class="control-label form-control text-center" type="text" placeholder="Enter your email address ...">
<button type="submit" class="btn btn-primary" data-toggle="modal" data-target="#myModal">Send</button>
</div>
</form>
<!-- Sart Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
<i class="material-icons">clear</i>
</button>
<h4 class="modal-title">Thank you</h4>
</div>
<div class="modal-body">
<p>Thank you for registering, we have added you to the waiting list!
</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger btn-simple" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- End Modal -->
And here is php code
<?php
$to = "test#test.com";
$from = "no-reply#test.com";
$headers = "From: " . $from . "\r\n";
$subject = "New Beta Subscription";
$body = "New user interested in beta program: " . $_POST['email'];
if( filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) )
{
if (mail($to, $subject, $body, $headers, "-f " . $from))
{
echo "<script type='text/javascript'>
$(document).ready(function(){
$('#myModal').modal('show');
window.stop();
});
</script>";
}
else
{
echo 'There was a problem with your e-mail (' . $_POST['email'] . ')';
}
}
else
{
echo 'There was a problem with your e-mail (' . $_POST['email'] . ')';
}
Also want to change Error messages to show up over modals also, that have it generated just not sure if can call two modals from same index file?
Any help is highly welcome!
Thanks, K>
What you are trying to achieve seems different from what you actually coded.
Let's look at your HTML form. You have attached Bootstrap's data-toggle and data-target attributes on your submit button. This means that when you click that button, it will open the modal AND submit the form. So the user will briefly see a modal and see the page redirect to your PHP file. (This is why you are seeing a modal appear briefly.)
Next, let's look at your PHP file. First of all, when you submit a form from one page to another page, that latter page has no idea of the HTML elements in your former page. This means the code you have inside your echo'd <script> tag actually should not be working as it is looking for an HTML element on your former page.
Now, for your question as to why are you getting a blank page? Well... everything is working fine so your code echo's a <script> tag -- which has no visual indicator. But like I just said, what you have inside the <script> does not work -- so nothing shows up and nothing happens.
So recap of the order of events when you click your button: the modal shows up, the form submits, the form redirects to another page, and that other page echo's nothing.
Below is a poor/quick solution to what I think you are trying to achieve:
Change your HTML file to a PHP file.
Remove data-toggle and data-target attributes off your button, so that it doesn't open the modal right when you click the button
<form action="form.php" method="post">
<div class="form-group label-floating">
<input name="email" class="control-label form-control text-center" type="text" placeholder="Enter your email address ...">
<button type="submit" class="btn btn-primary">Send</button>
</div>
</form>
Move your echo'd script tag from your PHP submission page to your PHP form page and wrap it in a condition as shown below:
<?php if (!empty($_GET['success'])) : ?>
<script>
$(document).ready(function(){
$("#myModal").modal();
});
</script>
<?php endif ?>
Remove your echo'd script tag lines of code in your PHP submission page. Instead, add a code so that it redirects back to your PHP form page. The key part is that you will append a ?success=true at the end of your URL.
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL); // valid email or null|false
if ($email) {
$to = "test#test.com";
$from = "no-reply#test.com";
$headers = "From: " . $from . "\r\n";
$subject = "New Beta Subscription";
$body = "New user interested in beta program: " . $email;
if (mail($to, $subject, $body, $headers, "-f " . $from)) {
header('Location: subscribe.php?success=true'); // replace `subscribe.php` with PHP form page
exit;
}
echo 'There was a problem with your e-mail (' . $email . ')';
} else {
echo 'There was a problem with your e-mail'; // no point in printing $email if it is null
}
Basically, passing ?success=true is for telling the PHP form page that everything went well to open the modal (3).
And that should be it.
A better approach is to learn and use AJAX.

Prevent bootstrap modal from closing after form submit

I have searched all over the net and did find some solutions but they all used JS or AJAX and helped to an extent only. I am new to PHP and have no clue about AJAX so if someone here could provide me with a solution using PHP & HTML or at most JS.
I have a very simple subscription form inside a bootstrap 3 modal in the footer section of my client's website. The PHP for it verifies that the subscriber is using their official or company email address only to subscribe and some other common/simpler validations.
The form is working great but the issue is that as soon as the person clicks on submit the modal closes and the user doesn't get to see the success or failure message until they reopen the modal from the trigger button. I want the modal to stay open even after the user submits the form and display whether the form submission was a success or not. I hope I was able to explain my issue properly. Here's my HTML & PHP for your reference:
HTML:
<div id="footer">
<div class="container">
<div class="col-md-6">
<div id="SubscribeModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">✕</button>
</div>
<div class="modal-body">
<?php include('subscribe.php') ?>
</div>
<div class="modal-footer"></div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dalog -->
</div><!-- /.modal -->
<a data-toggle="modal" href="#SubscribeModal" class="text-muted">Subscribe</a>
</div>
</div>
</div>
PHP:
<?php
if(isset($_POST['subscribe'])){
/* Configuration */
$subject = 'Please subscribe me to your Risk Alerts. Thank you.'; // Set email subject line here
$mailto = 'xyz#company.com'; // Email address to send form submission to
/* END Configuration */
if(empty($_POST['firstname'])){
$error = "Please add your first name";
}elseif(empty($_POST['lastname'])){
$error = "Please add your last name";
}elseif(empty($_POST['email'])){
$error = "Please add your business email";
}else{
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
// HTML for email to send submission details
$body = "
<br>
<p>The following information was submitted through the contact form on your website:</p>
<p><b>Name</b>: $firstname $lastname<br>
<b>Email</b>: $email<br>
";
$headers = "From: $firstname $lastname <$email> \r\n";
$headers .= "Reply-To: $email \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = "<html><body>$body</body></html>";
//build list of not allowed providers as lowercase
$NotAllowedClients = array("aol","applemail","comcast","entourage","gmail","hotmail","outlook");
preg_match_all('/\#(.*?)\./',$email,$clientarr);
$client = strtolower($clientarr[1][0]);
if(in_array($client,$NotAllowedClients)){
//Failed
$notice = "<div class=\"row-fluid\">
<div class=\"span12\">
<h3>Subscription Failed!</h3>
<p>Please use an official/company email address to subscribe. Try again</p>
</div>
</div>";
}else{
//Passed
//echo $message;
mail($mailto, $subject, $message, $headers);
$notice = "<div class=\"row-fluid\">
<div class=\"span12\">
<h3>Subscription successful!</h3>
<p>Thank you for taking the time to subscribe to our weekly Risk Alerts.</p>
</div>
</div>";
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Risk Alerts</title>
</head>
<body>
<?php
if(isset($notice)){
echo $notice;
}else{
//Show error for missing field
if(isset($error)){echo $error;}
?>
<div class="thumbnail center well well-small text-center">
<form id="subscription" method="post" action="" class="validate" novalidate>
<div class="row">
<div class="col-xs-6 col-md-6">
<input type="text" name="firstname" value="" class="form-control input-md" placeholder="your first name" />
</div>
<div class="col-xs-6 col-md-6">
<input type="text" name="lastname" value="" class="form-control input-md" placeholder="your last name" />
</div>
</div><p></p>
<input type="text" value="" name="email" class="form-control" placeholder="your email address" required /><br />
<div class="clear">
<input type="submit" value="Subscribe" name="subscribe" class="btn btn-md btn-primary button" />
</div>
</form>
</div>
<?php
}
?>
</body>
</html>
I haven't check your actual PHP but assuming it works, I would submit the form with ajax and process the response.
So, try the following:
Add an ID to your modal content:
<div class="modal-body" id="modal_content">
<?php include('subscribe.php') ?>
</div>
Then change your submit button to this :
Subscribe
Then add this jquery to the bottom of your form page (replace DIRECT_URL_TO_SUBSCRIBE with the correct url):
jQuery(function ($){
$('#submit_button').click(function(){
var post_url = 'DIRECT_URL_TO_SUBSCRIBE.php';
$.ajax({
type : 'POST',
url : post_url,
data: $('#subscription').serialize(), //ID of your form
dataType : 'html',
async: true,
beforeSend:function(){
//add a loading gif so the broswer can see that something is happening
$('#modal_content').html('<div class="loading"><img scr="loading.gif"></div>');
},
success : function(data){
$('#modal_content').html(data);
},
error : function() {
$('#modal_content').html('<p class="error">Error in submit</p>');
}
});
})
});
I was trying to figure out a similar issue so I'll leave this for future googles.
Add to PHP:
<?php
$keepOpen="";
if(isset($notice)){
$keepOpen="<script> $('#SubscribeModal').modal('show'); </script>";
Add to HTML:
<?php echo $keepOpen; ?>
Hi this works,
**data-backdrop="static"**
add that to bootstrap modal class. That should solve the issue for you.
<button type="button" data-backdrop="static" data-toggle="modal"
data- target="#yourID">Subscribe</button>

how do I get the message after submit to appear inside the pop up instead of on a different page

I have a contact form that I'm using Jquery .load to import a php file into any of the pages the nav will be on. Example below.
http://madaxedesign.co.uk/dev/index.html
I'm aware that the action form needs to be changed so it is connected to the right place. But how would I do that if it is on different pages and imported into a page. Because at the moment it is set to contact.php but after it is submitted it goes to that page and doesn't import the message into the pop up. So really I need it to be the file name depending on what page it is on.
So I suppose the question is how do I get the message after submit to appear inside the pop up instead of on a different page?
Code:
<?php
$your_email = "maxlynn#madaxedesign.co.uk";
$subject = "Email From Madaxe";
$empty_fields_message = "<p>Please go back and complete all the fields in the form.</p>";
$thankyou_message = "<p>Thank you. Your message has been sent. We Will reply as soon as possible.</p>";
$name = stripslashes($_POST['txtName']);
$email = stripslashes($_POST['txtEmail']);
$message = stripslashes($_POST['txtMessage']);
if (!isset($_POST['txtName'])) {
?>
<form method="post" action="contact.php">
<div id="NameEmail">
<div>
<label for="txtName">Name*</label>
<input type="text" title="Enter your name" name="txtName" />
</div>
<div>
<label for="txtEmail">Email*</label>
<input type="text" title="Enter your email address" name="txtEmail" />
</div>
</div>
<div id="MessageSubmit">
<div>
<textarea maxlength="1200" title="Enter your message" name="txtMessage"></textarea>
<label for="txtMessage">Message</label>
</div>
<div>
<input type="submit" value="Submit" /></label>
</div>
</div>
</form>
<?php
}
elseif (empty($name) || empty($email) || empty($message)) {
echo $empty_fields_message;
}
else {
$referer = $_SERVER['HTTP_REFERER'];
$this_url = "http://".$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"];
if ($referer != $this_url) {
echo "You do not have permission to use this script from another URL, nice hacking attempt ;p.";
exit;
}
mail($your_email, $subject, $message, "From: $name <$email>");
echo $thankyou_message;
}
?>
You should use ajax, send the email without refreshing page.
What you want to do is only possible in javascript, this is a language that gets executed by the browser. Javascript self is a nasty language but there are many extensions/plugins to make this very easy like jQuery. i suggest you to learn this language, you will find a new world opening in web development ;-). eg: http://learn.jquery.com/
give your form an id:
<form method="post" id="test-form" action="contact.php">
so you can reference to it with jquery
now you can catch the form submit action with jQuery:
$('#test-form').submit(function() {
//send your data to your server and get the html data
$.post('contact.php', $(this).serialize(), function (data){
//here you can add the (html)data returned by the action to your page.
$('body').append(data); //append data to body of html page
})
return false; //stop form from going to the next page
});
this code is based on a javascript plugin: jQuery, if you want to do anything dynamic on your page without reloading the page, you need to use javascript.

PHP form not processing in process.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.

Categories