PHP contact form will just refresh the page after submission. - javascript

After searching for about 3 hours i still can't figure this one out.
I Have a html template with a contact form and im trying to make it work using a PHP script.
I changed the template to PHP and pasted the PHP form script in it. everything is working fine except the confirmation text.
After a successful submission it will just refresh the page instead of printing "Your mail has been sent successfuly ! Thank you for your feedback". i do not want a redirect, i just want it to print on the same page.
Any ideas?
I got a sample of my code.
<form action="<? echo $_SERVER['PHP_SELF']; ?>" id="contact-form" method="post" class="form afsana-form" role="form">
<div class="row">
<div class="col-sm-12 form-group">
<input class="form-control afsana-style" id="name" name="name" placeholder="name" type="text" required autofocus />
</div>
<div class="col-sm-12 form-group">
<input class="form-control afsana-style" id="email" name="email" placeholder="email" type="email" required />
</div>
<div class="col-sm-12 form-group">
<textarea class="form-control" id="message" name="message" placeholder="message" rows="5"></textarea>
</div>
<div class="col-sm-12 form-group">
<button class="btn btn-primary afsana-btn" name="submit" value="verzenden" type="submit">Verzenden <i class="ion-arrow-graph-up-right"></i></button>
</div>
</div>
</form>
<?php
if(isset($_POST["submit"])){
// Checking For Blank Fields..
if($_POST["name"]==""||$_POST["email"]==""||$_POST["message"]==""){
echo "Fill All Fields..";
}else{
// Check if the "Sender's Email" input field is filled out
$email=$_POST['email'];
// Sanitize E-mail Address
$email =filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate E-mail Address
$email= filter_var($email, FILTER_VALIDATE_EMAIL);
if (!$email){
echo "Invalid Sender's Email";
}
else{
$subject = (Contact_form);
$message = $_POST['message'];
$headers = 'From:'. $email . "\r\n"; // Sender's Email
$headers .= 'Cc:'. $email2 . "\r\n"; // Carbon copy to Sender
// Message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
// Send Mail By PHP Mail Function
mail("something#domain.com", $subject, $message, $headers);
echo "Your mail has been sent successfuly ! Thank you for your feedback";
}
}
}
?>

First, you have this: $subject = (Contact_form); which should throw an error, so I assume you have error reporting turned off. When developing, you should have error reporting on so you can see errors in your code... Else you are just working blind. I don't mean by throwing tacky error_reporting(0) in every file either, I mean to set your error reporting level to E_ALL in your php.ini.
You also have: $headers .= 'Cc:'. $email2 . "\r\n";
However, $email2 is not defined anywhere, so you would get an error here too.. which is why it's important to test with error reporting on.
See if this works:
<?php
$error = '';
if(isset($_POST['submit']))
{
if ( !empty($_POST['name']) && !empty($_POST['email']) && !empty($_POST['message']) )
{
$email = $_POST['email'];
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if ( $email = filter_var($email, FILTER_VALIDATE_EMAIL) )
{
$subject = '(Contact_form)';
$message = $_POST['message'];
$headers = 'From:'. $email . "\r\n"; // Sender's Email
$message = wordwrap($message, 70);
if ( $result = mail("something#domain.com", $subject, $message, $headers) ) {
$error = 'Success';
} else {
$error = 'There was an error sending your email!';
}
} else {
$error = 'Invalid Email Address!';
}
} else {
$error = 'Please fill all fields.';
}
}
?>
<p><?= $error ?></p>
<form action="" method="post">
<input type="text" name="name" value="" /><br />
<input type="email" name="email" value="" /><br />
<textarea name="message" rows="5"></textarea><br />
<input type="submit" name="submit" value="submit" />
</form>

Try to put in $subject just a string value like:
$subject = 'Test subject';
change also the following line to this (there is no $email2 defined):
$headers .= 'Cc:'. $email . "\r\n"; // Carbon copy to Sender
and give it a try. You can also put as first line of your code
<?php error_reporting(E_ALL); ?>
and check for errors when submiting the form.

Related

Stop contact form from replying in new tab. My OCD is fistfighting my ADD over contact form

this is my html, my php, and ajax for a contact form. It works great except it post the relpys in a new browser tab. I have spent hours trying to correct it. Please help.
html-
<!-- form fields -->
<form action="assets/php/contact.php" method="post" name="contactform" id="contactform" class=" animated out" data-animation="fadeInUp" data-delay="0">
<fieldset>
<div class="row">
<div class="col-md-6">
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<input class="form-control" type="text" name="name" id="name" placeholder="Name">
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<input class="form-control" type="email" name="email" id="email" placeholder="Email">
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<input class="form-control" type="text" name="subject" id="subject" placeholder="Subject">
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<textarea class="form-control" name="message" id="message" placeholder="Message..."></textarea>
</div>
</div>
</div>
</fieldset>
<!-- submit button -->
<div class="form-group">
<input type="submit" name="submit" value="Send message" id="submit" class="btn btn-sm btn-primary">
</div>
<div id="alert"></div>
</form>
PHP-
if(!$_POST) exit;
// Email address verification, do not edit.
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
if(trim($name) == '') {
echo '<div class="notification error clearfix"><p><strong>Attention!</strong> You must enter your name.</p></div>';
exit();
} else if(trim($email) == '') {
echo '<div class="notification error clearfix"><p><strong>Attention!</strong> Please enter a valid email address.</p></div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="notification error clearfix"><p><strong>Attention!</strong> You have entered an invalid e-mail address, try again.</p></div>';
exit();
}
if(trim($message) == '') {
echo '<div class="notification error clearfix"><p><strong>Attention!</strong> Please enter your message.</p></div>';
exit();
}
if(get_magic_quotes_gpc()) {
$message = stripslashes($message);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "joe.doe#yourdomain.com";
$address = "your#email.com";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = 'You\'ve been contacted by ' . $name . '.';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "You have been contacted by $name ." . PHP_EOL . PHP_EOL;
$e_content = "\"$message\"" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $name via email, $email";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<div class='notification success clearfix'><p>Thank you <strong>$name</strong>, your message has been submitted to us.</p></div>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
JS-
/* ==============================================
Contact Form
=============================================== */
$('#contactform').submit(function(){
var action = $(this).attr('action');
$("#alert").slideUp(750,function() {
$('#alert').hide();
$('#submit')
.after('<img src="assets/images/ajax-loader.GIF" class="contactloader" />')
.attr('disabled','disabled');
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
message: $('#message').val()
},
function(data){
document.getElementById('alert').innerHTML = data;
$('#alert').slideDown('slow');
$('#contactform img.contactloader').fadeOut('slow',function(){$(this).remove();});
$('#submit').removeAttr('disabled');
if(data.match('success') !== null) {
$('#name').val('');
$('#email').val('');
$('#message').val('');
}
}
);
});
return false;
});
I want error or success messages to show on the contact.html page and not open a new browser tab.
Thank you advance for help restore my sanity.
Cheers
You just need to prevent the default form submit from firing, which will post the content to the URL in your form action.
$('#contactform').submit(function(event){
event.preventDefault();
...
});

How do I fix the POST 405 error for an email form (PHP) hosted on http-server?

I am new to PHP and jQuery. I wanted to test the functionality for the email contact form in PHP that I call from my jQuery file. I have been filling in the details on the form correctly, however, whenever I press the "Submit" button, I get 405 error.
To be more precise, I get "POST http://192.168.87.1:8080/js/inc/contactformhandler.php 405 (Method Not Allowed)" from jquery-3.4.1.min.js:2. I am running my website on http-server !.
My HTML form:
<div class="row contact-form">
<div class="col-twelve">
<!-- form -->
<form name="contactForm" id="contactForm" method="POST">
<fieldset>
<div class="form-field">
<input name="contactName" type="text" id="contactName" placeholder="Name" value="" minlength="2" required="">
</div>
<div class="form-field">
<input name="contactEmail" type="email" id="contactEmail" placeholder="Email" value="" required="">
</div>
<div class="form-field">
<input name="contactSubject" type="text" id="contactSubject" placeholder="Subject" value="">
</div>
<div class="form-field">
<textarea name="contactMessage" id="contactMessage" placeholder="message" rows="10" cols="50" required=""></textarea>
</div>
<div class="form-field">
<button class="submitform">Submit</button>
<div id="submit-loader">
<div class="text-loader">Sending...</div>
<div class="s-loader">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
</div>
</div>
</fieldset>
</form> <!-- Form End -->
<!-- contact-warning -->
<div id="message-warning">
</div>
<!-- contact-success -->
<div id="message-success">
<i class="fa fa-check"></i>Your message was sent, thank you!<br>
</div>
</div> <!-- /col-twelve -->
</div> <!-- /contact-form -->
JS code where I try to load the contactformhandler.php:
/* local validation */
$('#contactForm').validate({
/* submit via ajax */
submitHandler: function(form) {
var sLoader = $('#submit-loader');
$.ajax({
type: "POST",
url: "js/inc/contactformhandler.php",
data: $(form).serialize(),
beforeSend: function() {
sLoader.fadeIn();
},
success: function(msg) {
// Message was sent
if (msg == 'OK') {
sLoader.fadeOut();
$('#message-warning').hide();
$('#contactForm').fadeOut();
$('#message-success').fadeIn();
}
// There was an error
else {
sLoader.fadeOut();
$('#message-warning').html(msg);
$('#message-warning').fadeIn();
}
},
error: function() {
sLoader.fadeOut();
$('#message-warning').html("Something went wrong with loader. Please try again.");
$('#message-warning').fadeIn();
}
});
}
});
contactformhandler.php:
<?php
//Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
require '../vendor/autoload.php';
// Replace this with your own email address
$siteOwnersEmail = 'krysbaran#gmail.com';
if(isset($_POST["submit"])) {
$name = trim(stripslashes($_POST['contactName']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Check Name
if (strlen($name) < 2) {
$error['name'] = "Please enter your name.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Please enter a valid email address.";
}
// Check Message
if (strlen($contact_message) < 15) {
$error['message'] = "Please enter your message. It should have at least 15 characters.";
}
// Subject
if ($subject == '') { $subject = "Contact Form Submission"; }
// Set Message
$message .= "Email from: " . $name . "<br />";
$message .= "Email address: " . $email . "<br />";
$message .= "Message: <br />";
$message .= $contact_message;
$message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";
// Set From: header
$from = $name . " <" . $email . ">";
// Email Headers
$headers = "From: " . $from . "\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";
if (!$error) {
mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'MyWebsiteEmail';
$mail->Password = 'MyPassword';
$mail->SMTPSecure = 'ssl'; //<---- THIS is the problem
$mail->Port = 465;
$mail->setFrom('MyWebsiteEmail', 'My Website');
$mail->addAddress($siteOwnersEmail, 'Krzysztof Baran');
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $message;
$mail->AltBody = 'test text';
try {
$mail->send();
echo 'OK';
}
catch (phpmailerException $e) {
echo $e->errorMessage();
} catch (Exception $e) {
$e->getMessage();
}
} # end if - no validation error
else {
$response = (isset($error['name'])) ? $error['name'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
echo $response;
} # end if - there was a validation error
}
?>
I expect the website to display box saying Your message was sent, thank you! but I am getting Something went wrong with loader. Please try again.
You should use form in .php file not in .html file

I don't know why google recaptcha isn't working in my php email form

I've used the folowing step by step guide:
http://acmeextension.com/integrate-google-recaptcha-with-php/.
But for some reason, the recaptcha doesnt call/show up on the site?
I've called the script in the footer using:
<script src='https://www.google.com/recaptcha/api.js' async defer >
I've tried putting the PHP code right above the email form but it still didn't work. So, I separated it and put it into the separate send_form_email.php page.
This is the email form in which I implemented the recaptcha:
<form name="contactform" method="post" action="send_form_email.php" class="mb-0">
<div class="row">
<div class="col-md-6">
<input type="text" class="form-control" name="first_name" maxlength="50" placeholder="First Name: *" required>
</div>
<div class="col-md-6">
<input type="text" class="form-control" name="last_name" maxlength="50" size="30" placeholder="Last Name:">
</div>
<div class="col-md-6">
<input type="text" class="form-control" name="telephone" maxlength="50" placeholder="Phone:">
</div>
<div class="col-md-6">
<input type="email" class="form-control" name="email" maxlength="80" placeholder="Email: *" required>
</div>
<div class="col-md-12">
<textarea class="form-control" name="comments" rows="3" maxlength="1000" placeholder="Message: *" required></textarea>
</div>
<div class="g-recaptcha col-md-12" data-sitekey="6LexIpoUAAAAAMMftZIWNkik8IqsLfZDCKQxO9XO"></div>
<div class="col-md-12">
<input type="submit" value="Send Now" name="Submit" class="btn btn--secondary btn--rounded">
</div>
</div>
</form>
This is the sendemail php file:
<?php
if(isset($_POST['email'])) {
// EDIT THE 2 LINES BELOW AS REQUIRED
$email_to = "[REMOVED]";
$email_subject = "Emailed from Webform";
function died($error) {
// your error code can go here
echo "We are very sorry, but there were error(s) found with the form you submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
// validation expected data exists
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['email']) ||
!isset($_POST['telephone']) ||
!isset($_POST['comments'])) {
died('We are sorry, but there appears to be a problem with the form you submitted.');
}
$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$email_from = $_POST['email']; // required
$telephone = $_POST['telephone']; // not required
$comments = $_POST['comments']; // required
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'The First Name you entered does not appear to be valid.<br />';
}
if(!preg_match($string_exp,$last_name)) {
$error_message .= 'The Last Name you entered does not appear to be valid.<br />';
}
if(strlen($comments) < 2) {
$error_message .= 'The Comments you entered do not appear to be valid.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response']))
{
$secret = '[REMOVED]';
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->success)
{
$succMsg = 'Your contact request have submitted successfully.';
}
else
{
$errMsg = 'Robot verification failed, please try again.';
}
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "First Name: ".clean_string($first_name)."\n";
$email_message .= "Last Name: ".clean_string($last_name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Telephone: ".clean_string($telephone)."\n";
$email_message .= "Comments: ".clean_string($comments)."\n";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
?>
<!-- include your own success html here -->
<p>Thank you for contacting us. We will be in touch with you very soon.</P>
<?php
}
?>
It should show recpatcha code according to the tutorial. In reality it doesn't.

Get input value and show it in new page after submit

I tried to show user input after they submit their form.
Here is the form looks like:
<form class="form-horizontal col-sm-12" name="enq" method="post" action="email/" >
<div class="form-group"><label>Name</label><input class="form-control required" name="name" placeholder="Your name" data-placement="top" data-trigger="manual" data-content="Must be at least 3 characters long, and must only contain letters." type="text"></div>
<div class="form-group"><label>Message</label><textarea class="form-control" name="message" placeholder="Your message here.." data-placement="top" data-trigger="manual"></textarea></div>
<div class="form-group"><label>E-Mail</label><input class="form-control email" name="email" placeholder="email#you.com (so that we can contact you)" data-placement="top" data-trigger="manual" data-content="Must be a valid e-mail address (user#gmail.com)" type="text"></div>
<div class="form-group"><label>Phone</label><input class="form-control phone" placeholder="999-999-9999" data-placement="top" data-trigger="manual" data-content="Must be a valid phone number (999-999-9999)" type="text"></div>
<div class="form-group"><input type="submit" class="btn btn-success pull-right" id="submit" name="submit"></input> <p class="help-block pull-left text-danger hide" id="form-error"> The form is not valid. </p></div>
</form>
Here is the PHP after the user submit:
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$query = $_POST['message'];
$email_from = $name.'<'.$email.'>';
$to="test#ymail.com";
$subject="Enquiry!";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From: ".$email_from."\r\n";
$message="
Name:
$name
<br>
Email-Id:
$email
<br>
Message:
$query
";
if(mail($to,$subject,$message,$headers))
header("Location:../success.php");
else
header("Location:../test.php?msg=Error To send Email !");
//contact:-your-email#your-domain.com
}
And here is success.php:
$name = $_POST['name'];
$email = $_POST['email'];
$query = $_POST['message'];
echo "<span class=\"alert alert-success\" >Your message has been received. Thanks! Here is what you submitted:</span><br><br>";
echo "<strong>Name:</strong> ".$name."<br>";
echo "<strong>Email:</strong> ".$email."<br>";
echo "<strong>Message:</strong> ".$query."<br>";
I could receive what the user sent in my email, but the problem is with success.php, I tried to use the above code, but what I got is undefined index.
Is there a way to show the input values in the new page after submit?
Use session variables or you could alternatively send the data through the URL and use $_GET on the success page (I probably don't suggest this though).
PHP after submit:
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$query = $_POST['message'];
$email_from = $name.'<'.$email.'>';
$to="test#ymail.com";
$subject="Enquiry!";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From: ".$email_from."\r\n";
$message="
Name:
$name
<br>
Email-Id:
$email
<br>
Message:
$query
";
if(mail($to,$subject,$message,$headers))
{
session_start();//Start the session
$_SESSION['name'] = $name; //Set name session
$_SESSION['email'] = $email; //Set email session
$_SESSION['query'] = $query; // Set query session
header("Location:../success.php");
}
else
{
header("Location:../test.php?msg=Error To send Email !");
}
}
?>
success.php
<?php
session_start();
echo "<span class=\"alert alert-success\" >Your message has been received. Thanks! Here is what you submitted:</span><br><br>";
echo "<strong>Name:</strong> ".$_SESSION['name']."<br>";//Use the session variables
echo "<strong>Email:</strong> ".$_SESSION['email']."<br>";
echo "<strong>Message:</strong> ".$_SESSION['query']."<br>";
?>
It essentially saves the data into variables that will work whenever sessions are started on alternative pages and can be called using $_SESSION.
You are redirecting to another page so the post values are not passed to the success page. What you could do it put them temporairy in a session

How to make javascript contact form submit correctly

html code:
Contact Me
<label for="Name">Name:</label>
<input type="text" name="name" id="Name" accesskey="N" tabindex="1">
<label for="Email">E-mail:</label>
<input type="text" name="email" id="Email" accesskey="E" tabindex="1">
<label for="Phone">Phone Number:</label>
<input type="text" name="number" id="Number" tabindex="1">
<label for="Comment">Comments</label>
<textarea type="text" name="comment" id="Comment" rows="27" cols="70" tabindex="1"></textarea>
<input id="mySubmit" type="submit" value="Submit">
</form>
</fieldset>
</div>
email.php
<?php
if (isset($_POST['submit'])) {
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if (!$email)
echo "<script type='text/javascript'>alert('Please enter a valid email address...');history.back();</script>";
else {
$to = "randomemail#gmail.com"; //change this to YOUR email address
$name = (isset($_POST['name'])) ? $_POST['name'] : "anonymous";
$number = (isset($_POST['number'])) ? $_POST['number'] : "none";
$comment = (isset($_POST['comment'])) ? $_POST['comment'] : "none";
$subject = "Message from $name via contact form";
$message = "Name: $name\nNumber: $number\nEmail: $email\nMessage: $comment";
$from = "From: " . $name . "<" . $email .">\r\n" .
"Reply-To: " . $email ."\r\n" .
"X-Mailer: PHP/" . phpversion();
if (mail($to, $subject, $message, $from))
header("Location: thanks.html");
else
echo "<script type='text/javascript'>alert('An unknown system error has occurred!');history.back();</script>";
}
}
?>
when you submit, it loads email.php, but only a white page, not the thanks.html that it should.
You forgot to name your submit field:
<input id="mySubmit" type="submit" value="Submit" name="submit">
^^^^^^^^^^^^^
Don't use form fields to detect a post. Use the 100% reliable:
if ($_SERVER['REQUEST_METHOD'] == 'POST') { ... }
instead. This will ALWAYS be true if a POST was performed. As you can see with your version, a simple typo or oversight will completely kill your logic.
First Empty your file and just put header("Location: thanks.html"); in your php tags. If it works then add the other lines progressively. you'll see the annoying line. Read about header on PHP reference website. It should be used carefully

Categories

Resources