Created
September 23, 2016 02:33
-
-
Save yagamicoder/0daedb3c8cafa61b13a4be3bc35c9fb4 to your computer and use it in GitHub Desktop.
Ajax form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//Initialize errors variable and array | |
$errors = array(); | |
$jsonError = ""; | |
//Initialize post values and clean data | |
if(isset($_POST['userName'])){$name = trim(strip_tags(addslashes($_POST['userName'])));} | |
if(isset($_POST['email'])){$email = trim(strip_tags(addslashes($_POST['email'])));} | |
if(isset($_POST['subject'])){$subject = trim(strip_tags(addslashes($_POST['subject'])));} | |
if(isset($_POST['message'])){$message = trim(strip_tags(addslashes($_POST['message'])));} | |
if(isset($_POST['honeypot'])){$honeypot = trim(strip_tags(addslashes($_POST['honeypot'])));} | |
//Simple form validation | |
if(empty($name)){ | |
$errors[] = "Name required. <br/>"; | |
} | |
if(empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)){ | |
$errors[] = "Email is invalid. <br/>"; | |
} | |
if(empty($subject)){ | |
$errors[] = "Please enter a subject. <br/>"; | |
} | |
if(empty($message)){ | |
$errors[] = "Message required. <br/>"; | |
} | |
if(!empty($honeypot)){ | |
$errors[] = "Go away you bad spam! <br/>"; | |
} | |
//----------------------------------- | |
//Loop through errors array. | |
//Since we can only send back only one | |
//key to the client at a time, we | |
//must store them into one variable | |
//------------------------------------- | |
foreach($errors as $error){ | |
$jsonError .= $error; | |
} | |
//If errors variable is not empty, show errors. Otherwise, send the mail to my email address | |
if(!empty($errors)){ | |
//Send back json encoded errors array to Javascript | |
echo json_encode(array("error" => $jsonError)); | |
}else{ | |
//Send back json encoded success message array | |
echo json_encode(array("success" => "Submission successful! <br/> | |
We will contact you using the email: <br/> | |
<span class='myemail'>$email</span> <br/> | |
Thank you $name!")); | |
//Mail message | |
$to = "example@gmail.com"; | |
$headers = "$email [$name]"; | |
mail($to, $subject, $message, $headers); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment