I have a html form that sends email, using phpMailer, after its submission. Everything works fine but i want to display a message on the form when the email is sent.
With my code, a message is displayed on an empty white page.
My php code:
<?php
$name = $_POST['name'] ?? '';
$email = $_POST['email'] ?? '';
$msg = $_POST['msg'] ?? '';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
$mail->Host='smtp.gmail.com';
$mail->SMTPDebug = 0;
$mail->isSMTP();
$mail->Port=587;
$mail->SMTPAuth=true;
$mail->SMTPSecure='tls';
$mail->Username='email#email.com';
$mail->Password='password';
$mail->setFrom($email, $name); // who send the email
$mail->addAddress('email#email.com'); // who recive the email
$mail->isHTML(true);
$mail->Subject = 'Portfolio response';
$mail->Body = $msg;
$mail->send();
echo 'Your message has been sent!';
} catch (Exception $e){
echo '';
}
?>
Your message has been sent! is obviously the message displayed.
Html form code:
<form action="mail-handler.php" method="POST" id="contact-form">
<span class="contacts-text" id="first-contacts-text">To get in touch with me, please compile this form.</span>
<span class="contacts-text">I will reply as soon as possible. Thank you!</span>
<ul class="form-content">
<li class="form-input">
<label for="name" class="label">Full name</label>
<input class="input" id="name" type="text" name="name" required>
</li>
<li class="form-input">
<label for="email" class="label">E-mail</label>
<input class="input" id="mail" type="text" name="email" required>
</li>
<li class="form-input">
<label for="msg" class="label">Insert text</label>
<textarea class="input" id="comment" type="text" name="msg" cols="30" rows="10" style="resize: none;" required></textarea>
</li>
<li class="form-input" id="last-input">
<input class="input" id="form-button" type="submit" value="submit" name="submit" onclick="sendEmail()">
</li>
</ul>
</form>
Thanks in advice!
First, change the name of your index.html to index.php, so it can be parsed by a PHP interpreter.
Next modiy your success statement body, i.e.:
try {
$mail->send();
header('Location: index.php?mailsent=1');
die(); // we don't want exactly anything after sending redirect header.
} catch (Exception $e){
echo '';
}
Finally in file with your form add the message if $_GET['mailsent'] variable is available.
HTML code of your page...
...
<?php
if (isset($_GET['mailsent']) && intval($_GET['mailsent']) == 1 ){
echo '<div class="messagesbox">Mail was sent</div>';
}
?>
<form action="mail-handler.php" method="POST" id="contact-form">
... your form body skipped here
</form>
Other options
If you don't want to pass arguments via GET array, you can try to use sessions.
Also, you can just create a static thankyou.html page and redirect the user there, after mail submitting
Also, if you move the whole PHP code for the form submittion into index.php you won't need to make redirects.
Finally, as you added - while it's one-page site you should also consider using AJAX probably with jQuery - that way you're will be able to submit the form without leaving the page, display messages without reloading, etc. Anyway, this topic is definitely too broad to be described in this answer and I can only suggest you get familiar with jQuery AJAX.
Related
I made a PHP contact form which sends an email to me.
And I would like to inform the user that the message had been sent after refreshing the page.
I was able to make a pop up only before refreshed the page, with this the problem was that if the user leaves the page before clicking ok, the message won't be sent.
This is my current code:
<?php
if(isset($_POST['submit'])){
$name = $_POST['name'];
$subject=$_POST['subject'];
$mailFrom=$_POST['mail'];
$message=$_POST['message'];
$mailTo = "something#something.org";
$headers = "From: ".$mailFrom;
$txt ="You have received an e-mail from".$name.".\n\n" .$message;
if ($name != '' && $mailFrom != '') {
if (mail ($mailTo, $subject, $message, $mailFrom)) {
echo '<p>Your message has been sent.</p>';
} else {
echo '<p>Something went wrong, go back and try again.</p>';
}
} else {
echo '<p>You need to fill in all required fields.</p>';
}
}
mail($mailTo,$subject,$txt,$headers);
header("Location: index.php") ;
?>
HTML:
<div class="modal-bg">
<div class="modal">
<form class="contact-form" action="contactform.php" method="post">
<h2>Contact Us!</h2>
<label for="name">Name: </label> </br>
<input type="text" name="name" placeholder="Your name"> </br>
<label for="email">E-mail</label> </br>
<input type="text" name="mail" placeholder="Your e-mail"> </br>
<label for="subject">Subject: </label> </br>
<input type="text" name="subject" placeholder="Subject"> </br>
<label for="message">Message: </label> </br>
<textarea name="message" class="message" placeholder="Message" rows="15" cols="50"></textarea> </br>
<button type="submit" name="submit"> SEND </button>
</form>
<span class="modal-close">X</span>
</div>
</div>
I used a different method. Made a PHP page which says it is successful and redirects it after 5 seconds
<html>
<head>
<meta http-equiv="refresh" content="5;URL=http://address.com">
</head>
<body>
<div id="messagesent">
<p>Message has been sent successfully<p>
<p> This page will be redirect after 5 seconds. Please wait ...<p>
</div>
</body>
</html>
Ok, so what you have there is something i have had trouble with in the past: you are redirecting with a PHP header method, which is part of a (mostly) server side language which ends all of its functions as soon as the page is loaded: what i mean by this is that the code you have there will redirect the user out of your page before alerts or messages can be given out.
What i suggest you do is a little something like this in PHP:
$alert = "this is an alert and gets set whenever something happens";
//instead of an alert you could also create the paragraph with a button which triggers the redirect.
echo
"
<script>
window.onload = function(){alert('$alert');}
//this will fire the alert and stop any other thing from happening before the alert is closed
window.location.href = "https://target_page.com";
//this redirects the user to the wanted page, NB: do use href as other methods may directly redirect without waiting for the alert to display
</script>
";
Let me know if this is what you were looking for :)
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.
This question already has answers here:
Send email with PHP from html form on submit with the same script
(8 answers)
Closed 7 years ago.
So here is the problem I am facing. I have created a pretty simple web form:
<form method="post" action="#">
<div class="field"> <label for="name">Name</label>
<input name="name" id="name" type="text"> </div>
<div class="field"> <label for="email">Email</label> <input
name="email" id="email" type="email"> </div>
<div class="field"> <label for="message">Message</label> <textarea
name="message" id="message" rows="4"></textarea> </div>
<ul class="actions">
<li><input value="Send Message" type="submit"></li>
</ul>
</form>
I need to know how I can use this form to send data inputed by the user to my email address admin#nue-tech.uk I am aware this can be done in PHP but am unsure how to approach this as I am unfamilliar with PHP. If someone could please point me in the right direction as to how this can be done, and also where I should place the PHP file relative to this, that'd be awesome!
You could copy the code below and paste it in your HTML file below your html. In your html you set the action attribute empty. Don't forget to change your file extension to .php
<?php
if(isset($_POST['submit'])){
$to = "admin#nue-tech.uk";
$from = $_POST['email'];
$name = $_POST['name'];
$subject = "Blablabla"; //Write whatever you want here
$message = $name . "wrote the following:" . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
header('location: thank-you.html'); //redirects the user to another page if the mail was send succesfully
} else {
header('location: contact.html'); //if it was not send succesfully it redirects to the contact page again
exit(0);
}
?>
In
header('location: contact.html');
you could also use
echo "Something went wrong. Try again later"
or something simular.
I would highly recommend you search and learn on W3Cschools or at php.net.
i I've been trying to get a .php that works with this HTML code for my website (template), I tried using my old .php from my old website and changing the details but that sadly lead to no avail.
I am clueless when it comes to .php and would really appreciate your help!
What would my .php have to contain?
<form action="#" id="contact-form">
<div id="success"></div>
<ul>
<li class="input-name">
<input type="text" id="name" class="required" placeholder="Name">
</li> <!-- END input-name -->
<li class="input-email">
<input type="text" id="email" class="email" placeholder="Email Address">
</li> <!-- END input-name -->
<li class="input-subject">
<input type="text" id="subject" placeholder="Subject">
</li> <!-- END input-name -->
<li class="input-subject">
<textarea rows="7" cols="50" id="message" class="required" placeholder="Message"></textarea>
</li> <!-- END input-name -->
</ul> <!-- END #contact -->
<button type="submit" class="btn btn-primary btn-lg pull-right">Send Message</button>
</form>
if you are not using ajax then write php file name in form action attribute currently there is #. then you php file will be called.
Change the below code
<form action="#" id="contact-form">
to
<form action="mailer.php" method="post" id="contact-form">
hope this will help.
You have to include the in action="#" the php file. example: action="contactForm.php". That's how the HTML code knows where to send the parameters.
Also, make sure your server supports the 'mail' function.
AND!
I have a good standard example for you of a well written mailing php file that I used. So you can check yourself for syntax issues.
<?php
require_once "Mail.php";
if(isset($_POST['email'])) {
$email = $_POST['email']; //this is how you get your variables from the HTML file. 'edit' is the id of the element.
$email_to = "yourEmail#example.com";
$host = "ssl://smtp.gmail.com:465"; //use your email host - this example is gmail based. (you can search for your own email host via google).
$username = 'username#example.pro';
$password = 'yourPass';
$email_subject = "You have a new email from $email via example.com website";
$message = $_POST['text'];
$headers = array ('From' => $email, 'To' => $email_to,'Subject' => $email_subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($email_to, $headers, $message);
if (PEAR::isError($mail)) {
echo($mail->getMessage());
} else {
echo("Message successfully sent!\n");
}
}
In case of sending emails with ajax - it's an other thing.. and I can help you with that too.
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.