I'm building an ajax/php contact form for my project with the following fields:
Name (required), Email (required), Subject (Not required) and Website (Not required)
Everything's working fine the only problem now is if the user doesn't type anything in Subject and or Website fields the email I receive shows those 2 fields like so:
Subject: (shows blank)
Website: (shows blank)
Is it possible not to show those 2 fields at all if the user didn't type anything so on the email I receive I only get:
Name: [user name]
Email: [user email address]
I'm just posting the PHP code as I believe it's something to do with PHP only and not the Ajax script:
<?php
$errorMSG = "";
// NAME
if (empty($_POST["name"])) {
$errorMSG = "Name is required ";
} else {
$name = $_POST["name"];
}
// EMAIL
if (empty($_POST["email"])) {
$errorMSG .= "Email is required ";
} else {
$email = $_POST["email"];
}
// SUBJECT
$subject = $_POST["subject"];
// WEBSITE
$website = $_POST["website"];
// MESSAGE
if (empty($_POST["message"])) {
$errorMSG .= "Message is required ";
} else {
$message = $_POST["message"];
}
$EmailTo = "[email protected]";
$Subject = "New Message Received";
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Website: ";
$Body .= $website;
$Body .= "\n";
$Body .= "Subject: ";
$Body .= $subject;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$email);
// redirect to success page
if ($success && $errorMSG == ""){
echo "success";
}else{
if($errorMSG == ""){
echo "Something went wrong :(";
} else {
echo $errorMSG;
}
}
?>
Thank you all!