I'm using mailto on a form to open the default email service and create an email. However, all the fields on the form look horrible when they appear on the email. I have three fields noun1, verb, noun2 and when they're submitted, on the body of the email it shows up as, for example
noun1= I
verb= ate
noun2= food
Is there some way to specify how to organize/display these variables on the email body when submit is clicked so that it is formatted on the email body as
I ate food
?
The form, by request:
<form id= "formx" method="post" action="mailto:email#email.com" enctype="text/plain">
<p><label for="id_noun1">noun1:</label>
<input id="id_noun1" type="text" name="noun1"/></p>
<p><label for="id_verb">Verb:</label>
<input id="id_verb" type="text" name="verb" /></p>
<p><label for="id_noun2">noun2:</label>
<input id="id_noun2" type="text" name="noun2"/></p>
<input type="submit" value="Submit" />
Well, thanks for the help everybody, I guess.
What I settled on was taking the input from the form, creating a new element via javascript, making a link and adjusting the href on the fly. Finally, I have a javascript click event that opens an email with the information formatted as I want.
var a= document.getElementById('a');
var b= document.getElementById('b');
var c= document.getElementById('c');
var link = document.createElement('a');
link.setAttribute('href', 'mailto:me.com'
+ '?subject= Subject' + '&body='+ 'I am a ' + a.value + ', I like to ' + b.value
+ ', I also like doing ' + c.value
);
link.click();
first of all i have to say email by just html or javascript will end up looking weird just use php instead it is also quiet easy:
/first make the variables of all the things you need
$naam = $_POST['vnaam'];
$mail = $_POST['email'];
$achternaam = $_POST['anaam'];
$tel = $_POST['telefoon'];
$message = $_POST['commentaar'];
$Name = $naam; //senders name
$email = $mail; //senders e-mail adress
$recipient = "receivers email"; //recipient
$mail_body = //add the variables and text here by using . u get the same as + in javascript ;
//mail body
$subject = "Contact formulier van: " . $naam . " " . $achternaam; //subject
$header = "From: ". $Name . " <" . $email . ">\r\n"; //optional headerfields
if ($_POST) {
mail($recipient, $subject, $mail_body, $header); //mail command
exit;
}
now the if statement is the most important part. it is the part where the mail function is requested from. the pros of php is that the receiver doesnt get an email with something like:
idname=Dave
or idcheckbox=true or false (weither or not he box is checked)
Related
I have minimal knowledge in php and js. Im trying to get value from my form once submit button has been click then trigger my php script.
Js file:
document.getElementById('form')
.addEventListener('submit', function (event) {
event.preventDefault();
let response = grecaptcha.getResponse();
if (validateFields() && !response.length == 0) {
console.log('got here');
var data = new FormData(document.getElementById('form'));
var xhr = new XMLHttpRequest();
xhr.open('POST', 'form-to-email.php');
xhr.onload = function () {
console.log(this.response);
};
xhr.send(data);
return false;
}
document.getElementById('button').style.cursor = 'not-allowed';
});
Here's my php script:
<?php
// Google reCAPTCHA API key configuration
$siteKey = 'siteKey';
$secretKey = 'secretKey';
if (isset($_REQUEST['submit'])) {
$to = "example#mail.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$subject = "Form submission";
$message = $name . " wrote the following:" . "\n\n" . $_POST['message'];
if (isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])) {
// Verify the reCAPTCHA response
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=' . $secretKey . '&response=' . $_POST['g-recaptcha-response']);
// Decode json data
$responseData = json_decode($verifyResponse);
// If reCAPTCHA response is valid
if ($responseData->success) {
$headers = "From:" . $name . '<' . $from . '>' . PHP_EOL;
$headers .= "Reply-To:" . $to . PHP_EOL;
$headers .= "MIME-Version 1.0" . PHP_EOL;
$headers .= "Content-Type: text/html; charset=UTF-8" . PHP_EOL;
$headers .= "X-Mailer: PHP/" . phpversion();
$status = mail($to, $subject, $message, $headers);
echo "<pre>";
var_dump($status);
if ($status) {
echo '<p>Your message has been sent. We will get in touch with you soon. Thank you!</p>';
} else {
echo '<p>Something went wrong. Please try again!</p>';
}
} else {
echo 'error';
}
} else {
echo 'Please check on the reCAPTCHA box.';
}
}
?>
Here's my form code in index.php. I have 3 fields name, email and message:
<?php include_once 'form-to-email.php';?>
<form id="form" method="post" action="">
<div class="input-group">
<input type="text" id="name" name="name" class="input-demo" placeholder="Your Name">
<span id="invalid-name">
Please enter at least 2 chars
</span>
</div>
<div class="input-group">
<input id="email" type="email" name="email" class="input-demo" placeholder="Email Address">
<span id="invalid-email">
Please enter valid email
</span>
</div>
<div class="input-group">
<textarea id="message" name="message" placeholder="Message">
</textarea>
<span id="invalid-message">
Please write something for us
</span>
</div>
<div class="g-recaptcha" data-sitekey="<?php echo $siteKey; ?>">
</div>
<input type="submit" name="submit" id="button" class="demo" value="Book a Demo">
</form>
I get console.log empty values. Is this the right path or calling php is simply not doable?
Update
It now echos true and message sent.
Based on your question you are looking simply to submit a form and access the value in your php script. But it seems you are trying to submit the form via an ajax request. The first place to start is in your javascript code. The first thing I see is that you are calling a couple functions that are not defined so you never pass the if check and get to where it is supposed to say 'got here':
let response = grecaptcha.getResponse();
if (validateFields() && !response.length == 0) {
console.log('got here'); // you never get to this point
grecaptcha is not yet defined and I don't see any function definition for validateFields() so that fails as well. As a temporary fix while you are debugging it, comment out the if check like this so you can focus on the xhr request:
document.getElementById('form')
.addEventListener('submit', function (event) {
event.preventDefault();
// Comment out the following two lines
// so you can focus on getting the XHR request to work
// let response = grecaptcha.getResponse();
// if (validateFields() && !response.length == 0) {
console.log('got here');
var data = new FormData(document.getElementById('form'));
var xhr = new XMLHttpRequest();
xhr.open('POST', 'form-to-email.php');
xhr.onload = function () {
console.log(this.response);
};
xhr.send(data);
return false;
// } Comment out the closing bracket to match the comments from above
document.getElementById('button').style.cursor = 'not-allowed';
});
Ok, now when you hit submit, you should be sending the form data to your php script. To test out what shows up in the php script you can bail out early to see the contents of your $_POST variable.
<?php
// Google reCAPTCHA API key configuration
$siteKey = 'siteKey';
$secretKey = 'secretKey';
// Echo out the word success to make sure you got to this point.
// Then echo out the contents of your $_POST variable to see what is in it.
echo "Success";
var_dump($_POST);
exit; // exiting here bails out early.
// When you var_dump out your $_POST variable you will notice that
// $_POST['submit'] is not set since you don't have an input field
// for that value.
if (isset($_POST['submit'])) {
$to = "example#email.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$subject = "Form submission";
$message = $name . " wrote the following:" . "\n\n" . $_POST['message'];
. . .
Now, since you decided to do this via ajax, it will be a bit trickier to see the echo statement and the var_dump. To find out if it is working you need to use your dev tools network tab (F12 -> Network). Under the network tab you will see something like this:
Each time you hit submit, it should show a new line representing that request to the server. You can select a line and inspect the payload, preview, response tabs to see what was sent and what was received.
I hope this helps point you in the right direction. I'm not going to get into the issues with validating re-captcha and form validation. Those are topics for another question once you get the basic form working.
Cheers!
Based on this answer, change the way you're calling the php function.
document.getElementById('form')
.addEventListener('submit', function (event) {
event.preventDefault();
let response = grecaptcha.getResponse();
if (validateFields() && !response.length == 0) {
var data = new FormData(document.getElementById('form'));
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
}
xhr.open('POST', 'form-to-email.php?submit'); //don't forget submit here
xhr.send(data);
}
document.getElementById('button').style.cursor = 'not-allowed';
});
Also, try using $_REQUEST instead of $_POST in PHP file, as in:
if (isset($_REQUEST['submit'])) {
echo 'HERE IN PHP';
}
have been a while since i posted last thanks, in advance for all your help in the past..i have a single email box with a submit button.
What i want to do is to check this email address to make sure its not empty, if it is to display a message and then ask user to enter the valid email address which i want to validate so that it is only hotmail and gmail accounts e.g. xyz#hotmail.com and xyz#gmail.com and nothing else..
my code below works ok to check for empty and does display alert message on screen but i do not know how to manpulate the email address check and if all is ok how to use the same one submit button to submit the valid email with thank u popup message after submissions..thanks in advance...singhy
ps: apologises in advance for any beginners mistake i have made ...sorry
<?php
if(isset($_POST['email'])) {
$to = 'xyz#hotmail.com';
$subject = '';
$email = $_POST['email_from'];
//$message = "LIST \r\n".
$message = "signoff list name \r\n";
}
$email_from = $_POST['email'];
// create email headers
$message = wordwrap($message, 100, "\r\n");
$headers = 'From: '.$email."\r\n".
'Reply-To: '.$email."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($to, $subject, $message, $headers);
?>
<p>If you would like to receive our weekly newsletter email address below.</p>
<script type="text/javascript">
function IsEmpty(){
if(document.forms['isgtest'].email_from.value == "")
{
alert("Email field is empty, please enter email format");
return false;
}
//return submit "email_from.value";
(document.forms['test'].email_from.value == "subscribe")
//return .email_from.value == "";
//alert("thank u for joining the list !");
//return true;
}
</script>
<!--<script type="text/javascript"></script>-->
<form name="isgtest" class="rform" method="post" action="g.php">
<fieldset><legend>testing...</legend>
<label for="email_from"><span style="color: #ff0000;"><strong>*</strong>
</span>Email address:<input id="email_from" type="text" name="email_from" size="25" /> <input id="insert" id="btn" onclick="return IsEmpty();" style="float: right;" type="button" name="submit" value="Subscribe" /></fieldset>
</form>
If you are going for frontend validation (which should only be used to improve the user experience, never trust user input and always validate at the server side!), why not use the HTML5 features that exist for exactly that purpose. Something like this:
<form>
<label>Email:
<input type='email' pattern=".+(#gmail.com|#hotmail.com)" required />
</label>
<button type="submit">subscribe</button>
</form>
type=email makes sure only email addresses are accepted
required makes sure a value is provided before it can be submitted
pattern accepts a regex to which the input needs to comply before it can be submitted.
Personally I'm not a big fan of the default error messages my browser produces, but I'm even less of a fan of the alerts you are using, so...
If you insist on going the javascript way, I would advise something like this (pseudo code, untested):
function isEmpty(input) { ... }
function isEmail(input) { ... }
function isGmailOrHotmail(input) { ... }
function isValid(node) {
var value = node.value;
return ! isEmpty(value) && isEmail(value) && isGmailOrHotmail(value);
}
And then you could bind the isValid function to your submit button (preferably from your script file or block, but the inline onclick way should work as well)
<?php
$email_from = $_POST['email'];
$errors=array(); //track the errors as the script runs
function isValidEmail($addr) // Check for a valid email
{
return filter_var($addr, FILTER_VALIDATE_EMAIL) ? TRUE : FALSE;
}
if(!isValidEmail($email_from))$errors[]='Please enter a valid email address';
//Next, test for the email provider you wanted to filter by
$atPos=strpos($email_from,'#');//find the # symbol
$afterAt=substr($email_from,$atPos,strlen($email_from)-$atPos); //get everything after
$dotPos=strpos($afterAt,'.');
$domain=strtolower(substr($afterAt,0,$dotPos)); //get the typed domain, lowercase
if($domain!='hotmail'||$domain!='gmail')$errors[]='Email must be hotmail or gmail';
if(isset($_POST['email'])) {
if(count($errors)<0)
{
$to = 'xyz#hotmail.com';
$subject = '';
$email = $_POST['email_from'];
//$message = "LIST \r\n".
$message = "signoff list name \r\n";
// create email headers
$message = wordwrap($message, 100, "\r\n");
$headers = 'From: '.$email."\r\n".
'Reply-To: '.$email."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($to, $subject, $message, $headers);
}
}// note that I changed the nesting to only trigger the mail on post
?>
<p>If you would like to receive our weekly newsletter email address below.</p>
<script type="text/javascript">
function IsEmpty(){
if(document.forms['isgtest'].email_from.value == "")
{
alert("Email field is empty, please enter email format");
return false;
}
//return submit "email_from.value";
(document.forms['test'].email_from.value == "subscribe")
//return .email_from.value == "";
//alert("thank u for joining the list !");
//return true;
}
</script>
<!--<script type="text/javascript"></script>-->
<?php
if(count($errors)>0)
{
foreach $errors as $e //Now tell the user what went wrong
{
echo "$e<br>"; // you can also use '' to enclose js tags and use alert
}
}
?>
<form name="isgtest" class="rform" method="post" action="g.php">
<fieldset><legend>testing...</legend>
<label for="email_from"><span style="color: #ff0000;"><strong>*</strong>
</span>Email address:<input id="email_from" type="text" name="email_from" size="25" /><input id="insert" id="btn" onclick="return IsEmpty();" style="float: right;" type="button" name="submit" value="Subscribe" /> </fieldset>
</form>
I am making a call to a jQuery Mobile form to a simple PHP mailing file. I have tested the PHP file using the same data I am passing from the ajax call, which works just fine. However, when using ajax, the email is not sent and the address bar contains the query string. I really need more sets of eyes looking a this, since my mine seem permanently crossed.
Form Excerpt
<form id="hipaa-form" name="hipaa-form" autocomplete="on" data-ajax="false">
<p data-role="fieldcontain">
<label for="name">Name:<span class="smallred">*</span></label>
<input type="text" name="name" id="name" autofocus required placeholder="Full Name">
</p>
<p>
<input type="submit" name="send" id="send" style="cursor:pointer" value="Submit">
</p>
</form>
JavaScript
$('#hipaa-form').on('submit', function (e) {
var data = $(this).serialize();
$.ajax({
type: "GET",
url: email.php,
data: data,
dataType: "text",
success: function (result) { alert(result); },
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert("Error: " + +err.Message)
}
});
});
Note the data variable is set correctly, and is the string that winds up in the address bar. The alert from the success function displays the entire web page, but again the email is not sent. I tried setting custom error handlers in PHP, but they were no help at all.
PHP
$body = "Full Name: " . $_GET["name"] . "\r\n";
$body = $body . "email: " . $_GET["email"] . "\r\n";
$body = $body . "Phone: " . $_GET["phone"] . "\r\n";
$body = $body . "website: " . $_GET["Website-URL"] . "\r\n";
$body = $body . "app. type: " . $_GET["pgm-type"] . "\r\n";
$body = $body . "uses DB: " . $_GET["uses-db"] . "\r\n";
$body = $body . "saves data: " . $_GET["stores-patient-data"] . "\r\n";
$body = $body . "db vendor: " . $_GET["database-vendor"] . "\r\n";
if (isset($_GET["db-other"]))
$body = $body . "other db: " . $_GET["db-other"] . "\r\n";
$to = "contact.us#bunkerhill.com";
$subject = "HIPAA Form Submission";
mail($to, $subject, $body, "From: contact.us#text.bunkerhill.com");
echo "Form Submitted"
?>
My test site is : http://test.bunkerhill.com/
TIA
You need to block the form from being submitted with preventDefault();
$('#hipaa-form').on('submit', function (e) {
e.preventDefault();
...
}
Your ajax request should use querystring parameters with a GET or, change to type: "POST" and adjust your PHP to use $_POST
Example:
type: "GET",
url: "page.php?foo=x&bar=y"
Or
type: "POST",
url: "page.php",
data: data
Lastly, I'm a little worried about this example including HIPAA information. You might want to consider an approach where you store the information in a secure location and simply send an email that says, "Hey a new message is available. Click here to authenticate against our secure system to read it." Not that there is anything absolutely wrong with your approach but it feels like there is additional HIPAA related liabilities to consider.
url param in your Ajax definition should be 'email.php' in quotes, so change
url: email.php
to
url: 'email.php'
Without that it's just sending a call to http://test.bunkerhill.com/ and your PHP code sending email is never invoked at all :)
I have created a form using Ninja Forms on my WordPress website. I have one long form, which I've divided into tabs. When the user clicks the first button to continue, I want to send an email with specific fields. The issue is that my variables don't show up in my email. I'm receiving blank emails.
I've tried a number of things including ajax and a separate sendme.php. Since I'm using Wordpress, I decided to use the wp_mail function.
Here's my code. The variables work in my jquery alerts, but still aren't passed to my email.
I included this in my header.
$("#cont-btn").on('click', function (e) {
e.preventDefault();
var name = $("#ninja_forms_field_30").val();
var company = $("#ninja_forms_field_76").val();
var title = $("#ninja_forms_field_75").val();
var email = $("#ninja_forms_field_33").val();
var phone = $("#ninja_forms_field_32").val();
$.ajax({
type: "POST",
url: "sendme.php",
data:{ name: name, company: company, title: title, email: email, phone: phone },
success: function(data){
console.log(data);
}
})
});
And this is the basis of my sendme.php
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$company = $_POST['company'];
$phone = $_POST['phone'];
$to = 'me#email.co';
$subject = 'Enterprise Quote (PT1)';
$message = 'Email: ' .$company ;
$headers = '';
mail($to, $subject, $message) or die('Error sending Mail'); //This method sends the mail.
?>
A few things:
I don't want to validate the form.
I don't want to submit the form.
I want the user to stay on page.
Any help would be greatly appreciated. Thanks.
You cannot mix PHP and Javascript in this fashion, you have to separate you php and trigger it using AJAX requests.
So first put the php code in a separate file:
send.php
<?php
$headers = 'From: Me Myself <me#example.net>';
$message = $_POST['et_contact_message'];
$message .= '
Name: ' . $_POST['ninja_forms_field_30'];
$message .= '
Company: ' . $_POST['ninja_forms_field_76'];
$message .= '
Email: ' . $_POST['ninja_forms_field_33'];
$message .= '
Phone: ' . $_POST['ninja_forms_field_32'];
wp_mail( 'myemail#company.com', 'Enterprise Get a Quote (PT1)', $message, $headers );
?>
Then in your JS (jQuery)
$("#cont-btn").on('click', function (e) {
e.preventDefault();
var formData = $('#the-form').serialize(); //replace 'the-form' with your form id
$.post('/link/to/send.php', formData, function(res){
});
});
My account was suspended because of SPAM several times and my host provider told me to check my website security. May be my forms are not secured enough. Do you think that this form can be used to send spam?
Here is my code:
<script type="text/javascript">
$(document).ready(function () {
$('#form').ajaxForm({
beforeSubmit: validate
});
function validate(formData, jqForm, options) {
var name = $('input[name=name]').fieldValue();
var email = $('input[name=email]').fieldValue();
var company = $('input[name=company]').fieldValue();
var location = $('input[name=location]').fieldValue();
var phone = $('input[name=phone]').fieldValue();
var message = $('textarea[name=message]').fieldValue();
if (!name[0]) {
alert('Please enter your name');
return false;
}
if (!company[0]) {
alert('Please enter the name of your organization');
return false;
}
if (!email[0]) {
alert('Please enter your e-mail address');
return false;
}
if (!phone[0]) {
alert('Please enter your phone number');
return false;
}
if (!location[0]) {
alert('Please enter your location');
return false;
}
if (!message[0]) {
alert('Please enter your message');
return false;
}
else {
$("#form").fadeOut(1000, function () {
$(this).html("<img src='note.png' style='position: relative;margin: 0 auto;width: 500px;left: 20px;top: 30px;'/>").fadeIn(2000);
});
var message = $('textarea[name=message]').val('');
var name = $('input[name=name]').val('');
var email = $('input[name=email]').val('');
var phone = $('input[name=phone]').val('');
var company = $('input[name=company]').val('');
var location = $('input[name=location]').val('');
}
}
});
</script>
html:
<form id="form" method="post" name="form" action="send.php">
<input id="name" type="text" name="name"/>
<input id="company" type="text" name="company"/>
<input id="email" type="text" name="email"/>
<input id="phone" type="text" name="phone"/>
<input id="location" type="text" name="location"/>
<textarea name="message" id="message" rows="10"></textarea>
<input class="submit" type="submit" value="send" name="submit"></input>
</form>
php:
<?php
if($_POST){
$email = $_POST['email'];
$name = $_POST ['name'];
$company = $_POST ['company'];
$phone = $_POST ['phone'];
$location = $_POST ['location'];
$message = $_POST ['message'];
// response hash
$ajaxresponse = array('type'=>'', 'message'=>'');
try {
// do some sort of data validations, very simple example below
$all_fields = array('name', 'email', 'message');
filter_var($email, FILTER_VALIDATE_EMAIL);
foreach($all_fields as $field){
if(empty($_POST[$field])){
throw new Exception('Required field "'.ucfirst($field).'" missing input.');
}
}
// ok, if field validations are ok
// now Send Email, ect.
// let's assume everything is ok, setup successful response
$subject = "Someone has contacted you";
//get todays date
$todayis = date("l, F j, Y, g:i a") ;
$message = " $todayis \n
Attention: \n\n
Please see the message below: \n\n
Email Address: $email \n\n
Organization: $company \n\n
Phone: $phone \n\n
Location: $location \n\n
Name: $name \n\n
Message: $message \n\n
";
$from = "From: $email\r\n";
//put your email address here
mail("...#yahoo.com", $subject, $message, $from);
//prep json response
$ajaxresponse['type'] = 'success';
$ajaxresponse['message'] = 'Thank You! Will be in touch soon';
} catch(Exception $e){
$ajaxresponse['type'] = 'error';
$ajaxresponse['message'] = $e->getMessage();
}
// now we are ready to turn this hash into JSON
print json_encode($ajaxresponse);
exit;
}
?>
Many thanks!
Your form would actually be not safe against bots, because you dont got any captcha or something.
2 Options for you:
Captcha
Captcha -> you got something to fill in -> you probably know this!:)
https://www.google.com/recaptcha
Honeypot
Honeypot means, you are adding hidden fields in your form. And if those hidden fields have changed - you know that a BOT has entered content in your form. Aswell, this is better than Captchas, because your User doesnt has to fill in a Captcha
I would prefer Honeypot, because I don't like forms, where i have to fill in a Captcha once or even twice, when I failed or the captcha wasnt readable.
http://haacked.com/archive/2007/09/11/honeypot-captcha.aspx/
I have a simple approach to stopping spammers which is 100% effective, at least in my experience, and avoids the use of reCAPTCHA and similar approaches. I went from close to 100 spams per day on one of my sites' html forms to zero for the last 5 years once I implemented this approach.
another option is what I did is to use a hide field and put the time stamp on it and then compare to the time stamp on the PHP side, if it was faster than 15 seconds (depends on how big or small is your forms) that was a bot...
Taking clue from the suggestions above, I am just putting a ready code for you to use.
HTML
<form id="form" method="post" name="form" action="send.php">
<input id="name" type="text" name="name"/>
<input id="company" type="text" name="company"/>
<input id="email" type="text" name="email"/>
<input id="checkbot" type="hidden" name="timestamp" value="" />
<input id="phone" type="text" name="phone"/>
<input id="location" type="text" name="location"/>
<textarea name="message" id="message" rows="10"></textarea>
<input class="submit" type="submit" value="send" name="submit"></input>
</form>
Javascript
<script type="text/javascript">
$(document).ready(function () {
/*Set current time on the hidden field.*/
$('#checkbot').val($.now());
$('#form').ajaxForm({
beforeSubmit: validate
});
function validate(formData, jqForm, options) {
var name = $('input[name=name]').fieldValue();
var email = $('input[name=email]').fieldValue();
var company = $('input[name=company]').fieldValue();
var location = $('input[name=location]').fieldValue();
var phone = $('input[name=phone]').fieldValue();
var message = $('textarea[name=message]').fieldValue();
if (!name[0]) {
alert('Please enter your name');
return false;
}
if (!company[0]) {
alert('Please enter the name of your organization');
return false;
}
if (!email[0]) {
alert('Please enter your e-mail address');
return false;
}
if (!phone[0]) {
alert('Please enter your phone number');
return false;
}
if (!location[0]) {
alert('Please enter your location');
return false;
}
if (!message[0]) {
alert('Please enter your message');
return false;
}
else {
$("#form").fadeOut(1000, function () {
$(this).html("<img src='note.png' style='position: relative;margin: 0 auto;width: 500px;left: 20px;top: 30px;'/>").fadeIn(2000);
});
var message = $('textarea[name=message]').val('');
var name = $('input[name=name]').val('');
var email = $('input[name=email]').val('');
var phone = $('input[name=phone]').val('');
var company = $('input[name=company]').val('');
var location = $('input[name=location]').val('');
}
}
});
</script>
PHP
<?php
if($_POST){
$email = $_POST['email'];
$name = $_POST ['name'];
$company = $_POST ['company'];
$phone = $_POST ['phone'];
$location = $_POST ['location'];
$message = $_POST ['message'];
$checkbot = $_POST['timestamp'];
$time_diff = time() - $checkbot;
//If Time difference is less than 15 sec it's a bot
if($time_diff < 15){
exit;
}
// response hash
$ajaxresponse = array('type'=>'', 'message'=>'');
try {
// do some sort of data validations, very simple example below
$all_fields = array('name', 'email', 'message');
filter_var($email, FILTER_VALIDATE_EMAIL);
foreach($all_fields as $field){
if(empty($_POST[$field])){
throw new Exception('Required field "'.ucfirst($field).'" missing input.');
}
}
// ok, if field validations are ok
// now Send Email, ect.
// let's assume everything is ok, setup successful response
$subject = "Someone has contacted you";
//get todays date
$todayis = date("l, F j, Y, g:i a") ;
$message = " $todayis \n
Attention: \n\n
Please see the message below: \n\n
Email Address: $email \n\n
Organization: $company \n\n
Phone: $phone \n\n
Location: $location \n\n
Name: $name \n\n
Message: $message \n\n
";
$from = "From: $email\r\n";
//put your email address here
mail("...#yahoo.com", $subject, $message, $from);
//prep json response
$ajaxresponse['type'] = 'success';
$ajaxresponse['message'] = 'Thank You! Will be in touch soon';
} catch(Exception $e){
$ajaxresponse['type'] = 'error';
$ajaxresponse['message'] = $e->getMessage();
}
// now we are ready to turn this hash into JSON
print json_encode($ajaxresponse);
exit;
}
?>
In theory it can be used to send spam, because there are only checks if fields have values and as long the fields have a value, it does not care whether the input was human or a bot. You could improve the security by adding captcha codes (http://www.captcha.net/), to validate if an individual filling in your form is a human.
Try using this Spam Checker.
Useful program written in Java which looks up for spam IP Addresses using DNS lookups. Hope so it helps.