I am trying to create ajax and php files so when a user enters data on the form it either displays an error message if its invalid or sends and email and displays a thank you message if it is valid. I am stuck and not sure why my code is not working, right now when I hit submit the page is just reloaded with no messages at all.
AJAX code:
$('document').ready(function () {
var request;
$('contact').submit(function(event) {
event.preventDefault();
if (request) {
request.abort();
}
var $form = $(this);
var $inputs = $form.find("inputs, select, buttons, textarea");
var serializedData = $form.serialize();
$inputs.prop("disabled", true);
request = $.ajax({
url: "../send_email.php",
type: "post",
data: serializedData
});
request.done(function (msg) {
alert(msg);
});
request.fail(function (jqXHR, textStatus, errorThrown) {
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
request.always(function () {
$inputs.prop("disabled", false);
});
});//contact event
});//document ready
PHP code:
<?php
if(isset($_POST['email'])) {
$email_to = "email#address.ca";
$email_subject = "Personal Website Contact Form";
$error_message = "";
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['email']) ||
!isset($_POST['comments']))
{
$error_message .= 'Please fill in all fields.\n'
}
else{
$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$email_from = $_POST['email']; // required
$comments = $_POST['comments']; // required
$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.\n';
}
$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.\n';
}
if(!preg_match($string_exp,$last_name)) {
$error_message .= 'The Last Name you entered does not appear to be valid.\n';
}
if(strlen($comments) < 2) {
$error_message .= 'The Comments you entered do not appear to be valid.\n';
}
if(strlen($error_message) == 0) {
$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 .= "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);
echo "Email Sent. Thank you, I will get back to you asap";
}
else{
echo $error_message;
}
}
}
?>
$('document')
should be:
$(document)
And I suspect
$('contact')
should be:
$('#contact')
Though we'd have to see your HTML to know for certain. What you have is looking for <contact> elements, of which there are none. Instead, I imagine you want to look for something like <form id="contact">.
These are also wrong:
$form.find("inputs, select, buttons, textarea")
HTML elements aren't pluralized:
$form.find("input, select, button, textarea")
You have to be specific about your selectors. jQuery isn't going to be able to guess what you mean if it's close enough. It has to be exact. There are many options to use in the selectors, it's good to familiarize yourself with the basics.
Related
I want to make a contact form using php and javascript and I'm having a hard time with the alert() function. What I want to do, is inform the user of what's happening in the back end. I noticed that my "echo" functions get prompted into the console and I want to make them visible as an alert() function.
Here is my javascript:
$(document).ready(function() {
$("#submit").click(function() {
console.log("button clicked");
var name = $("#name").val();
var adresse = $("#adresse").val();
var telephone = $("#telephone").val();
var email = $("#email").val();
var project_place = $("#project_place").val();
var message = $("#message").val();
$("#returnmessage").empty(); // To empty previous error/success message.
// Checking for blank fields.
if (name == '' || email == '' || telephone == '' || message == '') {
alert("Please fill out the required fields.");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("includes/mail.php", {
name1: name,
adresse1: adresse,
telephone1: telephone,
email1: email,
project_place1: project_place,
message1: message
}, function(data) {
console.log(data);
$("#returnmessage").append(data); // Append returned message to message paragraph.
if (data == "Email sent.") {
$("#frmContact")[0].reset(); // To reset form fields on success.
alert("Email sent.");
}
});
}
});
});
and here's my php:
<?php
// Fetching Values from URL.
$name = $_POST['name1'];
$adresse = $_POST['adresse1'];
$telephone = $_POST['telephone1'];
$email = $_POST['email1'];
$lieu_du_projet = $_POST['lieu_du_projet1'];
$message = $_POST['message1'];
$email = filter_var($email, FILTER_SANITIZE_EMAIL); // Sanitizing E-mail.
// After sanitization Validation is performed
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
if (!preg_match("/^[0-9]{10}$/", $telephone)) {
echo "Please, enter a valid number";
} else {
$subject = $name;
// To send HTML mail, the Content-type header must be set.
$headers = 'MIME-Version: 1.0' . "rn";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "rn";
$headers .= 'From:' . $email. "rn"; // Sender's Email
$headers .= 'Cc:' . $email. "rn"; // Carbon copy to Sender
$template = 'Hi ' . $nom . ","
. "\n\nThank you form contacting us,"
. "\nName: " . $name
. "\nAdresse: " . $adresse
. "\nTelephone: " . $telephone
. "\nEmail: " . $email
. "\nProject Place: " . $project_place
. "\nMessage: " . $message
. "\nThis is a confirmation email. "
. "\nWe'll get back to you as soon as possible";
$sendmessage = $template ;
// Message lines should not exceed 70 characters (PHP rule), so wrap it.
$sendmessage = wordwrap($sendmessage, 70);
// Send mail by PHP Mail Function.
mail("my#email.com", $subject, $sendmessage, $headers);
echo "Email sent.";
}
} else {
echo "Email invalid.";
}
?>
Any help would be appreciated, thanks a lot!
Sorry for the title gore I am a little over my head on this one and have tried everything I can find online. I'm trying to pass data via post to my sendjs.php file and I have an issue.
The ajax success function does not apply the if statement.
Live site here: www.diysoakwells.com.au (you can add an item and checkout to test).
I'm not even sure where to start to be honest so any information would be appreciated and I will update the post with any info as requested.
app.js
$(function() {
// Get the form.
var form = $("#ajax-contact");
// Get the messages div.
var formMessages = $("#form-messages");
var spinner = $("#spinner");
var submit = $("#submit");
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
//display the cog animation
$(spinner).removeClass("hidden");
//hide the submit button
$(submit).addClass("hidden");
jsonObj=[];
for(i=1;i<$(".item-price").length;i++)
{
var items={};
var itemname = $(".item-name").get(i);
var itemprice = $(".item-price").get(i);
var itemquantity = $(".item-quantity").get(i);
var itemtotal = $(".item-total").get(i);
items["name"] = itemname.innerHTML;
items["price"] = itemprice.innerHTML;
items["quantity"] = itemquantity.innerHTML;
items["total"] = itemtotal.innerHTML;
jsonObj.push(items);
}
console.log(items);
var formdata = {};
formdata["textbox"] = $("#textbox").val();
formdata["name"] = $("#name").val();
formdata["phone"] = $("#phone").val();
formdata["email"] = $("#email").val();
formdata["address"] = $("#address").val();
formdata["grandtotal"] = simpleCart.grandTotal();
var x =
{
"cart" : jsonObj,
"formdata" : formdata,
"captchaResponse" : $("#g-recaptcha-response").val()
};
//jsonString = jsonObj+formdata;
var y = JSON.stringify(x);
console.log(y);
var result = jQuery.parseJSON(y);
console.log(result);
// Serialize the form data.
//var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: "post",
url: "sendjs.php" ,
//url: $(form).attr("action"),
data: y,
contentType: "application/json; charset=utf-8",
traditional: true,
success: function (response) {
if(response=="Thank You! Your message has been sent.")
{
//remove the button animation
$(spinner).addClass("hidden");
$(formMessages).removeClass("error");
$(formMessages).addClass("success");
$("#textbox").val("");
$("#name").val("");
$("#email").val("");
$("#message").val("");
$("#phone").val("");
$("#address").val("");
}
else
{
$(formMessages).removeClass("success");
$(formMessages).addClass("error");
$(spinner).addClass("hidden");
$(submit).removeClass("hidden");
}
$(formMessages).text(response);
}
});
});
});
sendjs.php
<?php
//Debugging
//ini_set( 'display_errors', 1 );
//error_reporting( E_ALL );
//replaces file_get_contents due to restrictions on server
function get_data($url)
{
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
//turn url_fopen on due to restrictions on server
//ini_set('allow_url_fopen', true);
date_default_timezone_set('Australia/Perth');
$time = date ("h:i A");
$date = date ("l, F jS, Y");
$json = file_get_contents('php://input');
$obj = json_decode($json,true);
$captcha = $obj["captchaResponse"];
$captcha;
$secretKey = "scrubbed";
$ip = $_SERVER['REMOTE_ADDR'];
$response = get_data("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
//not used due to server restictions
//$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
echo "Please Click on the Captcha";
return false;
}
else
{
//echo $items;
$name = $obj["formdata"]["name"];
$phone = $obj["formdata"]["phone"];
$email = $obj["formdata"]["email"];
$textbox = $obj["formdata"]["textbox"];
$address = $obj["formdata"]["address"];
$grandtotal = $obj["formdata"]["grandtotal"];
$text = "<html style='font-family:arial'>
<body>
<h1 style='color:crimson;'>DIY Soakwells</h1>
<p>This order was submitted from www.diysoakwells.com.au on $date at $time</p>
<p>$name thank you for your order inquiry. Deliveries are normally every Friday, we will be in contact shortly to discuss your order and confirm a time.</p>
<p>An invoice will be issued after delivery for payment via bank transfer.</p>
<p>In the meantime if you haven't already seen it, you can take a look at www.soakwellcalculator.com.au to confirm the number of soakwells you ordered will be adequate.</p>
<br>
<h2 style='color:crimson;'>CUSTOMER DETAILS</h2>
<p><b>Email:</b>\n$email</p>
<p><b>Name:</b>\n$name</p>
<p><b>Phone:</b>\n$phone</p>
<p><b>Delivery Address:</b>\n$address</p>
<p><b>Message:</b>\n$textbox</p>
<br>
<h2 style='color:crimson;'>ORDER DETAILS</h2>";
$items_in_cart = count($obj["cart"]);
for($i=0; $i < $items_in_cart; $i++) {
$iname = $obj["cart"][$i]["name"];
$price = $obj["cart"][$i]["price"];
$quantity = $obj["cart"][$i]["quantity"];
$total = $obj["cart"][$i]["total"];
//display looped cart data
$items .= "<p>$iname x $quantity - $price <small>ea.</small> <b>Sub Total: </b> $total .</p>";
}
$final_total ="<br>
<p><b>Total: </b>$$grandtotal <small>inc. GST</small></p>
</body>
</html>";
//Email Content
$body = $text.$items.$final_total;
// Set the email subject.
$subject = "New order from $name";
// Build the email content.
$email_content = $body;
// Build the email headers.
$email_headers = 'MIME-Version: 1.0' . PHP_EOL;
$email_headers .= 'Content-Type: text/html; charset=ISO-8859-1' . PHP_EOL;
//$email_headers .= 'To:' . $name . '<' . $email . '>' . PHP_EOL;
$email_headers .= 'From: DIY Soakwells <orders#diysoakwells.com>' . PHP_EOL;
$email_headers .= 'CC: orders#diysoakwells.com.au' . PHP_EOL;
$email_headers .= 'Reply-To: DIY Soakwells <orders#diysoakwells.com.au>' . PHP_EOL;
$email_headers .= 'Return-Path: DIY Soakwells <orders#diysoakwells.com>' . PHP_EOL;
$email_headers .= 'X-Sender: DIY Soakwells <orders#diysoakwells.com.au' . PHP_EOL;
$email_headers .= 'X-Mailer: PHP/' . phpversion() . PHP_EOL;
//$email_headers .= 'X-Priority: 1' . PHP_EOL;
//validate Email
$email_check = filter_input(INPUT_POST, $email, FILTER_VALIDATE_EMAIL);
//Recipients
$to = $email;
if (mail($to, $subject, $email_content, $email_headers, '-forders#diysoakwells.com.au')) {
// Set a 200 (okay) response code.
//http_response_code(200);
echo "Thank You. Your order has been sent and a copy mailed to your inbox.";
} else {
// Set a 500 (internal server error) response code.
//http_response_code(500);
echo "There appears to be an issue with our server, please ring 0420 903 950 or email contact#diysoakwells.com.au.";
}
}
?>
Hope someone can give me some tips.
because your condition is response == "Thank You! Your message has been sent."
and your results are
"Please Click on the Captcha", "Thank You. Your order has been sent and a copy mailed to your inbox.", "There appears to be an issue with our server, please ring 0420 903 950 or email contact#diysoakwells.com.au.".
so all of your result will do else part
I'm looking for a way to redirect after submit depending on the echo
and i used the following code:
<?php
$to = "mymail#gmail.com";
$name = Trim(stripslashes($_POST['name']));
$email = Trim(stripslashes($_POST['email']));
$message = Trim(stripslashes($_POST['message']));
$subject = "New Client Call";
$body = 'name: ' .$name."\r\n";
$body = 'email: ' .$email."\r\n";
$body = 'message: ' .$message."\r\n";
$go = mail($to, $subject, $body, "From:<$email>");
if ($go) {
echo "Success";
}
else {
echo "error";
}
?>
<form action="index9.html" method="post" name="redirect" ></form>
<script> document.forms['redirect'].submit()</script>
but i have now two problems:
i am always getting "success" echo. even the client sending empty details.
i want to redirect to an error page with Javascript (if/else) and i don't now how.
BTW i am new in this field so:
I will appreciate your advise/help and be thankful.
You don't need javascript to achive this you can use pure php.
You can use error checking if a field is empty in the form as follows
validate.php
if(isset($_POST['submit'])){
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (isset( $nameErr) || isset($emailErr){
// you have a error
}
else {
$to = "mymail#gmail.com";
$name = Trim(stripslashes($_POST['name']));
$email = Trim(stripslashes($_POST['email']));
$message = Trim(stripslashes($_POST['message']));
$subject = "New Client Call";
....
This will check if "email" field is empty if it is it will promp a error "Email is required"
And then in your html you add the error
<form class="form-horizontal" action="validate.php" method="post">
<label for="email">Email: </label>
<input type="text" class="form-control input-sm" name="email">
<span class="error">* <br><?php echo $emailErr;?></span>
<input class="btn btn-info btn-lg" type="submit" name="submit" value="Submit">
</form>
Hope that helps
You seem to be on the right path, before throwing the arguments into the the mailer I would say you can do more sanity checking to make sure all values are entered, this way you avoid trying to send emails that you know will fail, so you fail early and notify the user, you may also see the error message the mail function returns in case of failure to make it easy to rectify any other issues by using the erorr_get_last() method.
echo error_get_last()['message'];
Note: php mail does not verify the headers given, so you have to be 100% sure it's clean and there are no possibilities for the user to inject their own headers, so make sure you sanitize that too.
Then to do redirecting you can just directly replace the echo "success" and echo "error" calls with your javascript part.
So the script would finally look like this:
<?php
$to = "mymail#gmail.com";
$name = Trim(stripslashes($_POST['name']));
$email = Trim(stripslashes($_POST['email']));
$message = Trim(stripslashes($_POST['message']));
$subject = "New Client Call";
$missingFieldCount = 0;
if(!isset($_POST['name'])) {
echo "Error: Name requried";
$missingFieldCount++;
}
if(!isset($_POST['email'])) {
echo "Error: Email required";
$missingFieldCount++;
}
if(!isset($_POST['message'])) {
echo "Error: message required";
$missingFieldCount++;
}
if($missingFieldcount > 0) {
echo "Please fill in the missing $missingFieldcount fields, then submit again";
} else {
$body = 'name: ' .$name."\r\n";
$body .= 'email: ' .$email."\r\n"; // Using .= to append instead of replace
$body .= 'message: ' .$message."\r\n";
$headers = "From:<$email>"; //Make sure $email is actually just an email address and not injected headers
$success = mail($to, $subject, $body, $headears);
if ($success) {
$redirectPage = "successPage.html"
} else {
$redirectPage = "errorPage.html"
echo "An error occured:";
//Don't show this to the user, but log it to file instead
//this is here only for demonstration
echo error_get_last()['message'];
}
echo "<form action="$redirectPage" method="post" name="redirect" ></form>";
echo "<script> document.forms['redirect'].submit()</script>";
}
}
?>
Tnq Guys for your answers.
finally i manged a perfect PHP form from all the information i get in this issue. no need Javascript to redirect TO 2 different pages:
1. Thank you page.
2. error page.
and the code is like this:
<?php
$name = Trim(stripslashes($_POST['name']));
$email = Trim(stripslashes($_POST['email']));
$message = Trim(stripslashes($_POST['message']));
$to = "mymail#gmail.com";
$subject = " New Client order ";
$errors = 0;
$body ="";
$body .="Name: ";
$body .=$name;
$body .="\n";
$body .="Email: ";
$body .=$email;
$body .="\n";
$body .="Message: ";
$body .=$message;
$body .="\n";
if(isset($_POST['submit'])) { // Checking null values in message.
$name = $_POST["name"]; // Sender Name
$email = $_POST["email"]; // Sender's email ID
$message = $_POST["message"]; // Sender's Message
if (empty($_POST["name"])){
$nameError = "Name is required";
$errors = 1;
}
if(!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL))
{
$emailError = "Email is not valid";
$errors = 1;
}
if (empty($_POST["message"])){
$messageError = "Message is required";
$errors = 1;
}
}
if($errors == 0){
$successMessage = mail($to, $subject, $body, "From: <$email>");
}
else {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.html\">";
}
if ($successMessage){
print "<meta http-equiv=\"refresh\" content=\"0;URL=thanks.html\">";
}
?>
I've tried so many variables and been at this for hours and hours for something I know will be so simple haha, but I cannot get this to work... All I need to do, is... when the form is completed I have it redirected to a page instead of the normal error message.
Your help is appreciated.
<?php
//Retrieve form data.
//GET - user submitted data using AJAX
//POST - in case user does not support javascript, we'll use POST instead
$name = ($_GET['name']) ? $_GET['name'] : $_POST['name'];
$phone = ($_GET['phone']) ? $_GET['phone'] : $_POST['phone'];
$email = ($_GET['email']) ?$_GET['email'] : $_POST['email'];
$comment = ($_GET['comment']) ?$_GET['comment'] : $_POST['comment'];
//flag to indicate which method it uses. If POST set it to 1
if ($_POST) $post=1;
//Simple server side validation for POST data, of course, you should validate the email
if (!$name) $errors[count($errors)] = 'Please enter your name.';
if (!$phone) $errors[count($errors)] = 'Please enter your contact number.';
if (!$email) $errors[count($errors)] = 'Please enter your email.';
if (!$comment) $errors[count($errors)] = 'Please enter your comment.';
//if the errors array is empty, send the mail
if (!$errors) {
//recipient - replace your email here
$to = 'me#myemail.com';
//sender - from the form
$from = $name . ' <' . $email . '>';
//subject and the html message
$subject = 'Message from ' . $name;
$message = 'Name: ' . $name . '<br/><br/>
Phone: ' . $phone . '<br/><br/>
Email: ' . $email . '<br/><br/>
Message: ' . nl2br($comment) . '<br/>';
//send the mail
$result = sendmail($to, $subject, $message, $from);
//if POST was used, display the message straight away
if ($_POST) {
if ($result)
echo 'Thank you! We have received your message.';
else
echo 'Sorry, unexpected error. Please try again later';
//else if GET was used, return the boolean value so that
//ajax script can react accordingly
//1 means success, 0 means failed
} else {
echo $result;
}
//if the errors array has values
} else {
//display the errors message
for ($i=0; $i<count($errors); $i++) echo $errors[$i] . '<br/>';
echo 'Back';
exit;
}
//Simple mail function with HTML header
function sendmail($to, $subject, $message, $from) {
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: ' . $from . "\r\n";
$result = mail($to,$subject,$message,$headers);
if ($result)
return 1;
else
return 0;
}
This script is driving me up the wall. It's a simple submission form. I click the "submit" button and the email with all the submitted information is generated perfectly fine.
But I can't get the button to then redirect me to the "Thank You" page.
I've tried PHP, I've tried Javascript, I've even tried good old fashioned Meta Redirect. Nothing works.
// 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);
header("location:http://amvleague.vitaminh.info/thankyou.html")
}
die();
?>
I've tried putting the "header" part at the top of the document. I've tried changing it to:
echo '<script>document.location="page2.html"; </script>';
I've generated so many emails with this script that gmail is now sending them all to spam. And I can't get the damn thing to redirect.
If anyone can help before I claw my eyes out, it would be much obliged. ^_^;;
EDIT: I've tried everything you've all suggested. It's as if the script just flat-out refuses to execute anything that comes after the mail command. Could there be a reason for this?
EDIT 2: Still nothing's working.
Here's the entire script (with Rolen Koh's modifications). Is there something hidden in here that is preventing the script from accessing anything that comes after the mail tag?
<?php
if(isset($_POST['email'])) {
$email_to = "pathos#vitaminh.info";
$email_subject = "BelleCON 2014 - AMV League Submission";
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['handle']) ||
!isset($_POST['amv_title']) ||
!isset($_POST['amv_song']) ||
!isset($_POST['amv_artist']) ||
!isset($_POST['amv_anime']) ||
!isset($_POST['amv_link']) ||
!isset($_POST['amv_category']) ||
!isset($_POST['email'])) {
died('We are sorry, but there appears to be a problem with the form you submitted.');
}
function IsChecked($chkname,$value)
{
if(!empty($_POST[$chkname]))
{
foreach($_POST[$chkname] as $chkval)
{
if($chkval == $value)
{
return true;
}
}
}
return false;
}
$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$handle = $_POST['handle']; // not required
$amv_title = $_POST['amv_title']; // required
$amv_song = $_POST['amv_song']; // required
$amv_artist = $_POST['amv_artist']; // required
$amv_anime = $_POST['amv_anime']; // required
$amv_link = $_POST['amv_link']; // required
$amv_category = $_POST['amv_category']; // required
$email_from = $_POST['email']; // 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($error_message) > 0) {
died($error_message);
}
$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 .= "Name: ".clean_string($first_name).clean_string($last_name)."\n";
$email_message .= "Handle: ".clean_string($handle)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Title of AMV: ".clean_string($amv_title)."\n";
$email_message .= "Category: ".clean_string($amv_category)."\n";
$email_message .= "Song: ".clean_string($amv_song)." by ".clean_string($amv_artist)."\n";
$email_message .= "Anime Used: ".clean_string($amv_anime)."\n\n";
$email_message .= clean_string($amv_link)."\n";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
$mail = mail($email_to, $email_subject, $email_message, $headers);
if($mail)
{
header("location:http://amvleague.vitaminh.info/thankyou.html");
}
}
}
?>
You can use the header() function to send a new HTTP header, but this must be sent to the browser before any HTML or text (so before the <!DOCTYPE ...> declaration, for example).
try this,this is what I am using
function redirect($url){
if (headers_sent()){
die('<script type="text/javascript">window.location.href="' . $url . '";</script>');
}else{
header('Location: ' . $url);
die();
}
}
Try this:
$mail = mail($email_to, $email_subject, $email_message, $headers);
if($mail)
{
header("location:http://amvleague.vitaminh.info/thankyou.html");
}
Also semi-colon is missing in your header("location:http://amvleague.vitaminh.info/thankyou.html") line but i guess it is typo error.
use location.href
echo '<script>window.location.href="page2.html"; </script>';
The window.location object can be written without the window prefix.
The line
header("location:http://amvleague.vitaminh.info/thankyou.html")
Needs to be
header("Location: http://amvleague.vitaminh.info/thankyou.html");
Note the capital "L", the space after the colon, and the semicolon at the end.
If this does not resolve your issue, then you have an issue in some other piece of code. To find it, you might try looking at the php error log. If you have access to the server, you can find this by using any of the following resources for your particular server.
http://www.cyberciti.biz/faq/error_log-defines-file-where-script-errors-logged/
Where does PHP store the error log? (php5, apache, fastcgi, cpanel)
Where can I find error log files?
If you are on a shared host, they might have some non-standard location for this file, in which case, it might be easiest to contact them and ask where their standard location of the php error log is.