Ajax/PHP contact form issue - php

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#myemail.com";
$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!

You can check for conditions with an if statement. Something like this:
if (!empty($subject)) {
$Body .= "Subject: ";
$Body .= $subject;
$Body .= "\n";
}

You don't use formData, so disabling the field won't work.
If you want to get rid of empty variables, build the data according to a condition like this
function submitForm() {
var data = {
name: $("#name").val(),
email: $("#email").val()
}
if($("#subject").val() !== "") {
data.subject = $("#subject").val()
}
if($("#website").val() !== "") {
data.website = $("#website").val()
}
$.ajax({
type: "POST",
url: "php/form-process.php",
data: data,
success: function(text) {
if (text == "success") {
formSuccess();
} else {
formError();
submitMSG(false, text);
}
}
});
}

Related

Add a part of my form to the e-mail i receive using PHP

In my contact form i recently added a selector ( http://shopzuinig.nl/contact.html ) and styled it the way i wanted, but when i fill in the form and press send, the choice for a location is not included in the e-mail i receive. Can someone provide me with the PHP code to make this happen?
Here is my current PHP code:
<?php
error_reporting (E_ALL ^ E_NOTICE);
$post = (!empty($_POST)) ? true : false;
$replyto='restaurant#dellitalia.nl';
$subject = 'Verzoek via de website';
if($post)
{
function ValidateEmail($email)
{
$regex = "/([a-z0-9_\.\-]+)". # name
"#". # at
"([a-z0-9\.\-]+){2,255}". # domain & possibly subdomains
"\.". # period
"([a-z]+){2,10}/i"; # domain extension
$eregi = preg_replace($regex, '', $email);
return empty($eregi) ? true : false;
}
$name = stripslashes($_POST['name']);
$email = trim($_POST['email']);
$message = stripslashes($_POST['message']);
$phone = stripslashes($_POST['phone']);
$answer = trim($_POST['answer']);
$verificationanswer="6"; // plz change edit your human answer
$from=$email;
$to=$replyto;
$error = '';
$headers= "From: $name <" . $email . "> \n";
$headers.= "Reply-to:" . $email . "\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers = "Content-Type: text/html; charset=utf-8\n".$headers;
// Checks Name Field
if(!$name || !$email || $email && !ValidateEmail($email) || $answer <> $verificationanswer || !$message || strlen($message) < 1)
{
$error .= 'De velden zijn niet correct ingevuld.<br />';
}
if(!$error)
{
$messages.="Name: $name <br>";
$messages.="Email: $email <br>";
$messages.="Message: $message <br>";
$mail = mail($to,$subject,$messages,$headers);
if($mail)
{
echo 'OK';
if($autorespond == "yes")
{
include("autoresponde.php");
}
}
}
else
{
echo '<div class="error">'.$error.'</div>';
}
}
?>
Location Missing in your message. Include location to get location details in your mail.
if(!$error)
{
$mydropdown=$_POST['mydropdown'];
$mydropdown=mysql_real_escape_string($mydropdown);
$messages.="Name: $name <br>";
$messages.="Email: $email <br>";
$messages.="Message: $message <br>";
$messages.="Location: $mydropdown<br>"; // Missing. Include Location Here
$mail = mail($to,$subject,$messages,$headers);
if($mail)
{
echo 'OK';
if($autorespond == "yes")
{
include("autoresponde.php");
}
}
}

Two Form Post Actions - Pass data to another page AND email the data

I am currently working on a form that needs two post actions with one submit button. I am not extremely versed in PHP, only know enough to make my way around current tasks, until now.
Here is the code for the page the form is on:
<?php
if ($_POST) {
if (empty($_POST['first']) ||
empty($_POST['last']) ||
empty($_POST['email']) ||
empty($_POST['location'])) {
$errors = 1;
} elseif (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errors = 2;
} else {
$to = "emailgoeshere#gmail.com";
$subject = "Blah blah blah";
$message .= "Name: ".$_POST['first']." ".$_POST['last']."\n";
$message .= "Email: ".$_POST['email']."\n";
$message .= "Cell Phone: ".$_POST['cell']."\n";
$message .= "Location: ".$_POST['location']."\n";
$from = $_POST['email'];
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
header('Location: freepass.php');
exit;
}
}
if ($errors == 1) {
$errors = "Please fill out all fields";
} elseif ($errors == 2) {
$errors = "Please enter a valid email";
}
?>
This is the form action:
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
This is the code on the page that the data will pass to:
<html>
<head>
</head>
<body>
<?php echo $_POST["first"]; ?> <?php echo $_POST["last"]; ?>
<br>
<?php echo $_POST["email"]; ?>
<br>
<?php echo $_POST["cell"]; ?>
<br>
<?php echo $_POST["location"]; ?>
</body>
</html>
This is a very quick solution but it should do the trick.
if ($_POST) {
$errors = null;
$error_message = "<ul>";
if (empty($_POST['first']) ||
empty($_POST['last']) ||
empty($_POST['email']) ||
empty($_POST['location'])) {
$errors = 1;
}
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errors = 2;
}
if($errors == null) {
$to = "grimegriever#gmail.com";
$subject = "City Fitness 7-Day Pass Applicant";
$message .= "Name: ".$_POST['first']." ".$_POST['last']."\n";
$message .= "Email: ".$_POST['email']."\n";
$message .= "Cell Phone: ".$_POST['cell']."\n";
$message .= "Location: ".$_POST['location']."\n";
$from = $_POST['email'];
$headers = "From:" . $from;
mail($to, $subject, $message, $headers);
header('Location: freepass.php');
exit;
} else {
if ($errors == 1) {
$error_message .= "<li>Please fill out all fields</li>";
}
if ($errors == 2) {
$error_message .= "<li>Please enter a valid email</li>";
}
$error_message .= "</ul>";
}
}
I'm sure there are much more efficient solutions, but this will work.

strange behavior on contact form

I am having a strange problem with this form. I have made it yesterday night and it was working fine, sending all the emails as it should. However, I've run it today and it won't simply work at all. I am always getting the error message. Any clues? Thank you.
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$depart = $_POST['departamento'];
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
$corpo = "Nova Mensagem\n";
$corpo .= "De: " . $name . "\n";
$corpo .= "Email: " . $email . "\n";
$corpo.=" Para o departamento " . $depart. "\n";
$corpo .= "Mensagem: " . $message . "\n";
if ($depart = administrativo)
{
$email_to = '';
}
elseif ($depart = financeiro)
{
$email_to = '';
}
elseif ($depart = Suporte)
{
$email_to = '';
}
else
{
$email_to = '';
}
$status = mail($email_to, $subject, $corpo, $headers);
if($status) {
echo "<script> window.location.href = ''; </script>";
}
else {
echo "<script> window.location.href = ''; </script>";
}
?>
Instead of = use == for comparison
for example - instead of:
if( $depart = administrativo)
use
if( $depart == "administrativo" )
You should enclose strings within quotes. Moreover, == (comparing objects of different types) && === (comparing objects of same types) are used for comparing and = is used for assigning. So, change the code as follows (inside the if statements) :
if ($depart == 'administrativo')
{
$email_to = '';
}
elseif ($depart == 'financeiro')
{
$email_to = '';
}
elseif ($depart == 'Suporte')
{
$email_to = '';
}
else
{
$email_to = '';
}

Two PHP forms on same page

I have two php forms on same page now the problem is I am calling them through an iframe but there captcha is not working though I am using the same script for both the forms with different input fields. Right now what happens is when we click first time on captcha and write correct captcha it take us to YOU HAVE ENTERED WRONG CAPTCHA and then we fill correct captcha then show us thanku...Why not it shows thanks for the first time when we enter correct captch??????
<?php
session_start();
$tuCurl = curl_init();
curl_setopt($tuCurl, CURLOPT_URL, $url);
curl_setopt($tuCurl, CURLOPT_RETURNTRANSFER, 1);
$tuData = curl_exec($tuCurl);
curl_close($tuCurl);
$userip = explode(',',$tuData);
$ipcountry = str_replace('"', '', $userip[3]);
include "libmail.php";
$errors = '';
//print_r($_POST);
if(isset($_POST['email']))
{
if(empty($_SESSION['6_letters_code'] ) ||
strcasecmp($_SESSION['6_letters_code'], $_POST['captcha']) != 0)
{
$errors .= "You have entered wrong captcha code!";
}elseif($_FILES["userfile"]["size"] > 1048576)
{
$errors .= "You can upload maximum of 800kb file!";
}else{
$productsq = $_POST['productsq'];
$name = $_POST['name'];
$position = $_POST['position'];
$phone = $_POST['phone'];
$company = $_POST['company'];
$companyweb = $_POST['companyweb'];
$address = $_POST['address'];
$country = $_POST['country'];
$brief = $_POST['brief'];
$email = $_POST['email'];
$captcha = $_POST['captcha'];
$sender = $contact_email;
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
if(trim($productsq) !='')
$email_message .= "*I'm interested in : ".clean_string($productsq)."\n"."\n";
if(trim($name) !='')
$email_message .= "Full Name: ".clean_string($name)."\n"."\n";
if(trim($position) !='')
$email_message .= "Position/Title: ".clean_string($position)."\n"."\n";
if(trim($phone) !='')
$email_message .= "Phone: ".clean_string($phone)."\n"."\n";
if(trim($company) !='')
$email_message .= "Company Name: ".clean_string($company)."\n"."\n";
if(trim($companyweb) !='')
$email_message .= "Website URL: ".clean_string($companyweb)."\n"."\n";
if(trim($address) !='')
$email_message .= "Full Address: ".clean_string($address)."\n"."\n";
if(trim($country) !='')
$email_message .= "Country: ".clean_string($country)." (IP Address) : $ipcountry ".$_SERVER['REMOTE_ADDR']."\n"."\n";
if(trim($brief) !='')
$email_message .= "About Myself : ".clean_string($brief)."\n"."\n";
$random = mt_rand();
$m= new Mail; // create the mail
$m->From( $name."<$email>" );
$m->To( "abc#gmail.com" );
$m->Subject( "Form2 - ".$random );
$m->Body( $email_message);
$m->Priority(2) ;
if($_FILES["userfile"]["tmp_name"]){
move_uploaded_file($_FILES["userfile"]["tmp_name"], 'uploadedfiles/'.$_FILES["userfile"]["name"]);
$file_upload = 'uploadedfiles/'.$_FILES["userfile"]["name"];
$m->Attach( $file_upload) ;
}
$m->Send();
header('location:thankyou.php');
if($_FILES["userfile"]["tmp_name"]){
unlink($file_upload);
}
}
}
?>
A captcha image code is usually stored in a session variable. When you display the second form, you are overwriting the captcha from the first form.

How do I post back errors from the php script back to page

I have a simple contact form which uses jquery to post to a php page which sends an email. I would like the 'security code' error to post back to the html page if its not entered correctly. How do I do this?
Here's the PHP Script:
session_start();
if(($_SESSION['security_code'] != $_POST['security_code']) || (empty($_SESSION['security_code'])) ) {
$return['error'] = true;
$return['msg'] = 'Please re-enter the security code .';
}
else {
if ((isset($_POST['name'])) && (strlen(trim($_POST['name'])) > 0)) {
$name = stripslashes(strip_tags($_POST['name']));
} else {$name = 'No name entered';}
if ((isset($_POST['email'])) && (strlen(trim($_POST['email'])) > 0)) {
$email = stripslashes(strip_tags($_POST['email']));
} else {$email = 'No email entered';}
if ((isset($_POST['phone'])) && (strlen(trim($_POST['phone'])) > 0)) {
$phone = stripslashes(strip_tags($_POST['phone']));
} else {$phone = 'No phone entered';}
if ((isset($_POST['comments'])) && (strlen(trim($_POST['comments'])) > 0)) {
$comments = stripslashes(strip_tags($_POST['comments']));
} else {$comments = 'No comments entered';}
$contactByPhone = $_POST['contactByPhone'];
$contactByEmail = $_POST['contactByEmail'];
$contactNoPreference = $_POST['contactNoPreference'];
$state = $_POST['state'];
$email_to = "clinic#gmail.com";
$email_subject = "contact";
$email_message .= "Name: ".$name."<br/>";
$email_message .= "Email: ".$email."<br/>";
$email_message .= "Phone: ".$phone."<br/>";
$email_message .= "State: ".$state."<br/>";
$email_message .= "Comments: ".$comments."<br/>";
$email_message .= 'Contact By: '.$contactByPhone . ' ' . $contactByEmail . ' ' . $contactNoPreference."<br/>";
$email_message .= $_SERVER['HTTP_HOST'];
$headers = 'From: '.$email."\r\n".
'Reply-To: '.$email."\r\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
mail($email_to, $email_subject, $email_message, $headers);
unset($_SESSION['security_code']);
}
Here's the javascript file:
$(function() {
$('.error').hide();
$(".button").click(function() {
$('.error').hide();
var name = $("input#name").val();
if (name == "") {
$(".error").show();
return false;
}
var email = $("input#email").val();
if (email == "") {
$(".error").show();
return false;
}
var phone = $("input#phone").val();
if (phone == "") {
$(".error").show();
return false;
}
var comments = $("#comments").val();
if (comments == "") {
$(".error").show();
return false;
}
var security_code = $("#security_code").val();
if (security_code == "") {
$(".error").show();
return false;
}
var state = $("select#state option:selected").val();
var contactByPhone = $("#contactByPhone:checked").val();
var contactByEmail = $("#contactByEmail:checked").val();
var contactNoPreference = $("#contactNoPreference:checked").val();
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone + '&state=' + state + '&comments=' + comments + '&contactByPhone=' + contactByPhone
+ '&contactByEmail=' + contactByEmail + '&contactNoPreference=' + contactNoPreference;
$.ajax({
type: "POST",
url: "send_form_email.php",
data: dataString,
success: function() {
//alert (dataString);
$('#contact_form').html("<h2>Contact Form Submitted!</h2><br/><p>We will be in touch soon.</p>");
}
});
return false;
});
});
If You replace
success:function()...
to
success:function(data)
then whatever you echo in php script would be in data variable.
So You can echo error information and process it in this function.
Do an echo json_encode($results) to output your error message. Then have your Javascript check if data['error'] is set to true in the success handler.
Some people will say you should output an HTTP status code of 400 or some such to indicate an error, but I highly dislike the practice. Everything about the HTTP connection was fine. A request was made, the script ran, a response was generated. Everything at the HTTP layer worked perfectly, so indicating an error at this level is a dumb idea. It's like saying your car trip was a completely failure because the store didn't have the flavor of gum you wanted.

Categories