Given a standard html form such as the one below;
<form method="post" action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>>
<div class="row half">
<div class="6u"><input type="text" placeholder="Name" name="name" /></div>
<div class="6u"><input type="text" placeholder="Email" name="email" /></div>
</div>
<div class="row half">
<div class="12u"><textarea name="message" placeholder="Message" name="message"></textarea></div>
</div>
<div class="row">
<div class="12u">
<ul class="actions">
<li><input type="submit" class="button" value="Send Message" name="submit" /></li>
<li><input type="reset" class="button alt" value="Clear Form" name="clear"/></li>
</ul>
</div>
</div>
</form>
And the following php
if(isset($_POST['submit'])){
$to = "enquiries#appcloudkent.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$subject = "Website Enquiry";
$message = $name . " wrote the following:" . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
if(isValidString($from) && isValidString($name) && isValidString($message)){
mail($to,$subject,$message,$headers);
}
}
It is possible to send an email, however, this approach causes a couple of problems. Because my form is at the bottom of the page, when send is clicked the page is redirected back and the focus goes back to the top of the page.
What is the correct way to provide adequate user feedback to let the user know the email was sent, is it possible to navigate back to the page and automatically scroll to the bottom - allowing me to change the send button to green or something?
Failing that, is there a better approach to doing this?
Thanks
Add an anchor link before your form.
<a id="anchorName"></a>
Post your form to the anchor.
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>#anchorName">
The form action should point to the page itself (like it does in your example) so you can display error messages from validation (like you don't).
If the form is not at the top of your page you can add an anchor:
<h2><a name="theForm">The form</a></h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>#theForm">
If the form is processed properly (=mail sent), it is good practice to redirect to another page, showing a success message. So pressing F5 doesn't submit the form again (and send another mail).
if (mail($to,$subject,$message,$headers)) {
// redirect to page showing success message and exit script
} else {
// redirect to page showing error message and exit script
}
I usually redirect to the same page again, but attach an param ($_SERVER["PHP_SELF"].'?mail_success=1') and then inside the template I decide whether to show the success message, error message or the form:
if (isset($_REQUEST['mail_success'])) {
// show success message
} elseif (isset($_REQUEST['mail_error'])) {
// show error message, technical issues, try again bla bla
} else {
// show the form (including validation errors if necessary)
}
You could submit the form using an XMLHttpRequest, and cancel the default action of pressing submit. jQuery's .post() and event.preventDefault() methods are particularly good at that.
Related
I have put together a simple contact form for my website. Using PHP to POST the data and send directly to my email address. But for some reason every time I visit the page on my website. I still get the test message Displaying under the Form. Then when I reload the website and visit the link again it still displays the thank you message. and automatically sends an email. Im still in testing mode 2 days before my launch and I need this figure out. Considering I am novice to php I dont know what goes where.... check out my website to get a live view https://trillumonopoly.com (click "Contact Us" link in menu) I would like for the contact form to disappear and echo the thank you message once sent. And reset after the page is reloaded. I am also using Jquery ajax to load all my pages into a div container. So I would like to keep the content inside that div without forwarding to the Echo message page, leaving my index page
Heres My ajax code
$(document).ready(function () {
loadMainContent('main');
$('body').delegate('.navMenu', 'click', function (event) {
event.preventDefault();
loadMainContent($(this).attr('href'));
});
});
function loadMainContent(page) {
$('#main').load('pages/' + page + '.php');
}
here is html for the form:
<div class="general row container-fluid"><br>
<center><img src="img/divider.png" class="img-fluid"></center>
<div class="col-lg-6 col-sm-12">
<img src="img/logo.png" class="img-fluid" height="540px" width="540px">
</div>
<div class="col-lg-6 col-sm-12 container"><center>
<br><h1 class="form-title">Contact Us</h1><br></center>
<div class="container">
<form action="pages/mail.php" method="GET" class="box2">
NAME:
<input type="text" name="name" placeholder="YOUR NAME HERE" required>
<br><br>
EMAIL:
<input type="email" name="email" placeholder="YOUR EMAIL HERE" required>
<br><br>
MESSAGE:<br>
<textarea name="message" rows=10 cols=23 placeholder="YOUR MESSAGE HERE" required></textarea>
<br><Br>
<button type="submit" value="Message Sent" class="btn btn-danger btn-lg" style="background-color:"red">SUBMIT</button
</form>
<center><?php include('mail.php'); ?></center>
</div>
</div>
</div>
Here is My simple PHP:
<?php
$name = $POST['name'];
$email = $POST['email'];
$message = $POST['message'];
mail("info#trillumonopoly.com","ILLUMONOPOLY WEB Contact", $message,"From: $email\r\n");
echo "Thank You For Contacting Us!";
?>
Better than check everything before send mail.
if(isset($_POST['name']) && isset($_POST['email']) && isset($_POST['message'])){
$name = $POST['name'];
$email = $POST['email'];
$message = $POST['message'];
mail("info#trillumonopoly.com","ILLUMONOPOLY WEB Contact", $message,"From: $email\r\n");
echo "Thank You For Contacting Us!";
}
And send POST request to the index, not mail.php.
<form action="" method="POST">
...
So the user can see your message at the end of contact form.
My issue: I'm trying to make this form both email the form data and redirect to download page using php script (i.e.: One click = 2 actions). I searched the boards and didn't really find anything similar to what I am trying to do. I had tried several options code wise, but it won't send the email at all. What am I doing wrong?
code:
form:
<form id="myform">
<form method="get" action="action/php">
<fieldset><center>
<h3>DOWNLOAD DVD</h3>
<p> Enter your full name and email and then press Download DVD. </p>
<p><br>
<label>Enter Your Name *</label>
<input type="text" name="name" pattern="[a-zA-Z ]{5,}" maxlength="30" />
</p>
<p>
<label>Enter Your Email *</label>
<input type="email" name="email" required />
</p>
<button type="submit" id="submit-myform"; class="submit" value="Submit" name="myform_submit">Download DVD</button>
<button type="reset">Reset</button>
</fieldset>
</form>
php:
<?PHP
if(isset($_POST['myform_submit']) && $_POST['myform_submit'] == "Submit"){
echo "http://www.website.com";
}else {
mail( "info#website.com", "Landing Page Download",
$name, "From: $email" );
}
?>
Again ... The download content comes up nicely. But the email will not send.
I think you've got your if statement mixed up. Currently it's saying if the form is submitted, then print a URL to the screen, otherwise send an email but from what you've said you want to redirect and send an email. Try this:
if(isset($_POST['myform_submit'])) {
$send = mail( "info#website.com", "Landing Page Download", $_POST['name'], "From: " . $_POST['email'] );
if($send) {
header("Location: http://www.website.com");
} else {
echo 'Error sending email!';
}
}
Problem number 2 is you have nested forms. Not sure why you're doing this, but it's against HTML spec and will probably cause your form data not to get sent as it should. Remove the outer form. Here's line 3 of the HTML3(old!) spec:
Note you are not allowed to nest FORM elements!
Problem number 3, you're setting your form method as GET and then trying to access POST variables. Problem 3.5, your action is action/php - thats not a filename (unless you have an index.php file inside a folder called php, inside a folder called action). Change all this to:
<form method="post" id="myform" action="action.php">
Note: header("Location: [url]") sends a redirect header to your browser, so you are redirected to the target URL. If you simply want to display the URL (like in your question) then continue to just echo it.
My website is one pager with nav that links to different parts of the page within the same document. So my contact is at stie.com/#contact rather than site.com/contact.html
I have my contact form coded in html using post method linking to mail.php. Upon hitting the submit button I get redirected to site.com/mail.php where the "Your message was succesfully sent" is displayed. How do I get it so that it displays right on top of the contact form since I don't have a contact.html file to turn into a contact.php and put the php code right where I want the success message to display?
<div class="row">
<div class="12u">
<form method="post" action="mail.php">
<div>
<div class="row half">
<div class="6u">
<input type="text" name="name" id="name" placeholder="Name" />
</div>
<div class="6u">
<input type="email" name="email" id="email" placeholder="Email" />
</div>
</div>
<div class="row half">
<div class="12u">
<input type="text" name="subject" id="subject" placeholder="Subject" />
</div>
</div>
<div class="row half">
<div class="12u">
<textarea name="message" id="message" placeholder="Message"></textarea>
</div>
</div>
<div class="row">
<div class="12u">
Send Message
Clear Form
</div>
</div>
</div>
</form>
</div>
My Mail.php
<?php
//GET INFO FROM CONTACT FORM
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST ['subject'];
$message = $_POST['message'];
$from .= $_POST ['email'];
$to = 'email#site.com';
// compose headers
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
//POST SUBMIT
if ($_POST['sumbit']);
if ($name != '' && $subject != '' && $message !='' && $email != '') {
if (mail ($to, $subject, $from, $message, $headers)) {
echo '<p>Your message has been sent!</p>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
} else {
echo '<p>Please fill in all required fields!!</p>';
}
?>
You can use URL parameters with PHP:
<?php
$confDisplay = 'display:none;';
// if the url param exists, display confirmation
if(isset($_GET["confirm"]) && $_GET["confirm"]==true){
$confDisplay = 'display:inline;';
}
?>
...
<div style="<?php echo $confDisplay; ?>">
Your form has been submitted!
</div>
...
Just set your form action URL to the same page with ?confirm=true at the end.
Make your action field empty. Put action="" instead of action="mail.php" Then include your mail.php content inside your contact page. As you know, you have to save that page as PHP, too; for example, mycontactform.php. In this way you have more control over the content and format of the "your message submitted" message. If you separate mail.php you can't address divisions in the mycontactform.php.
Security and vulnerability of PHP codes you are using should be addressed after you have completed the page coding and tested it as up and running in your desired format, since it needs more in-depth study of PHP conventions and usages. source: A Set of Step by Step Tutorials Using HTML5, CSS3 and PHP (8)
Note that your script mail.php is vulnerable to headers injection attack. You need to escape your variable $_POST['email']. You have to remove the special characters \n and \r. This can be made easily by using the str_replace function.
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.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to stop form from sending email more times after initial success.
First of all, i have structured my website using directories. So basically every page is a directory and in that directory, i have a file called index.php.
I have four contact forms on my site, and at the moment, the seem to all work using the hnadler.php file. The handler file validates the data, checks the form-id posted and based on that, it routes the email appropraitely. A success message is displayed if successfully sent. However, my current implimentation is flawed in that if the user refreshes, another mail is sent. How can i solve this with my existing code? Thank you
//handler.php
<?php
if(isset($_POST['submit'])) {
//carry out validation
if(!isset($hasError)) {
//check the form id posted and set email address in $emailTo accordingly
$body = "Name: $name \n\nEmail: $email \n\nEnquiry: $enquiry";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
//index.php
<?php if(isset($hasError)) { ?>
<p class="error">Please make sure you have filled all fields with valid information. Thank you.</p>
<?php } ?>
<?php if(isset($emailSent) && $emailSent == true) { ?>
<p><strong>Your enquiry was sent successfully.</strong></p>
<p>Thank you for your enquiry! Your email was successfully sent and we will be in touch with you promptly.</p>
<?php }; ?>
<form id="contactform" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<fieldset>
<legend>Enquiry form</legend>
<label for="name">Name:</label><input type="text" size="50" name="name" id="name" value="" class="required" />
<label for="email">Email:</label><input type="text" size="50" name="email" id="email" value="" class="required email" />
<label for="enquiry">Enquiry:</label><textarea rows="5" cols="20" name="enquiry" id="enquiry" class="required"></textarea>
<input type="submit" name="submit" value="Submit enquiry" class="curved-btn"></input>
<input type="hidden" id="form-id" name="form-id" value="general"></input>
</fieldset>
</form>
?>
The problem is that you aren't actually submitting to handler.php because of this:
<form id="contactform" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Change it to this:
<form id="contactform" method="post" action="handler.php">
And put your send e-mail code inside of handler.php. You will also need to put a redirect in there to get them back to a page. There are other ways to go about this, but this is how I would do it.
The browser will/can repost the data on refresh, so it will look like a new request.
A quick fix is to redirect after the form submission:
header("Location: success.php");
That way if the refresh they refresh the success page, not the page you posted to.