我有一个 php 邮件表单。如果电子邮件地址未通过验证,我的 jquery 会使用成功消息更新 emailform div。如果表单成功提交(发布),我只希望出现成功消息。
jQuery:
$('#submit').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response) { // on success..
console.log(response);
if(response != 'error; you need to submit the form!'){
$('#emailform').html("<h2 style='text-align:center;'>Thank you!</h2><hr><p style='text-align:center;'>Thank you for submitting your purchase information.<br>We will send your free gifts soon!</p>"); // update the DIV
}
}
});
return false; // cancel original event to prevent form submitting
});
PHP:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
if(!isset($_POST['submit']))
{
//This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!";
}
$name = $_POST['name'];
$email = $_POST['email'];
$purchasecode = $_POST['purchasecode'];
$vendor = $_POST['vendor'];
//Validate first
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['purchasecode']) ||
empty($_POST['vendor']))
{
echo "All fields are required.";
exit;
}
if(IsInjected($email))
{
echo "Bad email value!";
exit();
}
$email_from = $email;
$email_subject = "GDFY Purchase Confirmation";
$email_body = "New purchase confirmation from $name.\n".
"Here are the details:\n\n Name: $name \n\n Email: $email \n\n Purchase Code: $purchasecode \n\n Vendor: $vendor";
$to = "idc615@gmail.com";//<== update the email address
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $email_from \r\n";
//Send the email!
mail($to,$email_subject,$email_body,$headers);
//done. redirect to thank-you page.
header('Location: index.html');
// echo "success";
// Function to validate against any email injection attempts
function IsInjected($str)
{
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str))
{
return true;
}
else
{
return false;
}
}
?>