In the following code, I have a contact form and in that form there is an email validation script. As a result of validation, I want the error message to be shown in a div called confirmation without reloading the page. Also, if the email is valid, the mail will be sent and I want the Thank you message to be shown in the same div confirmation. The problem is what can I do to prevent reloading the page and let the error message or the thanks message shows in the confirmation div?
<html>
<body>
<?php
function spamcheck($field) {
// Sanitize e-mail address
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
// Validate e-mail address
if(filter_var($field, FILTER_VALIDATE_EMAIL)) {
return TRUE;
} else {
return FALSE;
}
}
?>
<?php
if (!isset($_POST["submit"])) {
?>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
From: <input type="text" name="from"><br>
Subject: <input type="text" name="subject"><br>
Message: <textarea rows="10" cols="40" name="message"></textarea><br>
<input type="submit" name="submit" value="Submit Feedback"><br>
<div id="confirmation" style="display:none" align="center"></div>
</form>
<?php
} else { // the user has submitted the form
// Check if the "from" input field is filled out
if (isset($_POST["from"])) {
// Check if "from" email address is valid
$mailcheck = spamcheck($_POST["from"]);
if ($mailcheck==FALSE) {
echo"
<script>
document.getElementById('confirmation').text ='invalid email';
</script>";
} else {
$from = $_POST["from"]; // sender
$subject = $_POST["subject"];
$message = $_POST["message"];
// message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
// send mail
mail("nawe11#gmail.com",$subject,$message,"From: $from\n");
echo"
<script>
document.getElementById('confirmation').text ='Thank you';
</script>";
}
}
}
?>
</body>
</html>
Thanks
<input type="text" name="from" id ="from">
Call example:
var request = $.ajax({
url: "file.php",
type: "POST",
data: { email : $('#from').val() }
});
request.done(function( msg ) {
//handle HTML
});
request.fail(function( jqXHR, textStatus ) {
//Handle problem at server side
});
PHP Side
<?php
$email = $_POST["email"]
function spamcheck($field) {
// Sanitize e-mail address
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
// Validate e-mail address
if(filter_var($field, FILTER_VALIDATE_EMAIL)) {
return 'valid';
} else {
return 'no_valid';
}
}
echo spamcheck($email);
There's no way you could do that with just PHP.
What you're looking at is commonly known as AJAX, and uses client-side language (Javascript)
It's very common, and widely used on the internet. You can find many examples and production-ready scripts by searching ajax on google.
More informations here : http://www.w3schools.com/ajax/
Related
This is a password recovery form through HTML page that post data to PHP file via AJAX. Everything is okay with the code except once submitted and response recived, form input fields don't clear. I have been searching the web for the past 4 hours and found too many code lines to do so but none of them seems to work. plz help me in this matter :) have a good day.
$(function() {
/////////////////////////////////////////////////////////'Form ID' & 'Element Name' /////////////////////////////////////////
// Get the form.
var form = $('#emailform');
// Get the messages div.
var formMessages = $('#formresults');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
// $('#email1').val('');
//var email = $('input[name=#email]').val("");
//document.getElementById("emailform").reset();
//$('#emailform')[0].reset();
//$('input:text').val('');
//$('#emailform input[type=text]').val('');
//setTimeout(function(){
//$('input,textarea','#emailform').val(''); //clearing inputs
//},1);
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AJAX Contact Form Demo</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="page-wrapper">
<h1>AJAX Contact Form Demo</h1>
<div id="formresults"></div>
<form id="emailform" name="emailform1" method="post" action="exa.php">
<table align="center">
<tr><td><div class="input-append"><input type="text" name="email" id="email1" class="input-xlarge" placeholder="email" maxlength="100" /><span class="add-on"><li class="icon-envelope"></li></span></div></td></tr>
</table>
<!-- <hr /> -->
<center><input type="submit" name="Forget" id="btn" class="btn btn-primary Loading-btn" value="ٍSend" data-loading-text="Sending ..." /></center>
</form>
</div>
<script src="ajax/jquery-2.1.0.min.js"></script>
<script src="ajax/app.js"></script>
</body>
</html>
<?php
// Get Access to data base
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$email = $_POST["email"];
// Check that data was sent to the mailer.
if ( empty($email) ) {
// Set a 400 (bad request) response code and exit.
http_response_code(100);
echo "BLABLABLA.";
exit;
}
if ( !filter_var($email, FILTER_VALIDATE_EMAIL) ) {
// Set a 400 (bad request) response code and exit.
http_response_code(200);
echo "BLABLABLA.";
exit;
}
if (#mysql_num_rows(mysql_query("SELECT `id` FROM `accounts` WHERE `email`='$email'")) < 1) {
// Set a 400 (bad request) response code and exit.
http_response_code(300);
echo "BLABLABLA.";
exit;
}
$row_user = #mysql_fetch_array(mysql_query("SELECT * FROM `accounts` WHERE `email`='$email'"));
////////////////////////////
$password = $row_user['pass'];
$to = $row_user['email'];
$subject = "Your Recovered Password";
$message = "Please use this password to login: " . $password;
$headers = "From : XXX#XXX.XXX";
// Send the email.
if (mail($to, $subject, $message, $headers)) {
// Set a 200 (okay) response code.
http_response_code(400);
echo "BLABLABLA.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "BLABLABLA.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(600);
echo "There was a problem with your submission, please try again.";
}
?>
You can use JavaScript's .reset() function on the form element which will clear all input fields.
I found the answer, just removed http_response_code()
for all if statments .
Thx all for your help. I can sleep now knowing my day is not wasted :)
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 have managed to get ReCaptcha 2.0 working in my website. However, it's only working when I don't use AJAX and I let the form submit "naturally".
I want to submit the form with the captcha and alert the user with a success note without refreshing the page.
I tried the following code, but it seems like the server doesn't get the user response:
HTML:
<form class="form" action="javascript:void(0)" novalidate>
<!-- all the inputs... -->
<!-- captcha -->
<div class="input-group">
<div class="g-recaptcha" data-sitekey="6LdOPgYTAAAAAE3ltWQGar80KUavaR-JblgPZjDI"></div>
</div>
<div class="errors" id="errors" style="display: none"></div>
<div class="input-group">
<input type="button" value="Send" class="btn-default right" id="submit">
<div class="clear"></div>
</div>
</form>
JS:
$('#submit').click(function(e) {
console.log('clicked submit'); // --> works
var $errors = $('#errors'),
$status = $('#status'),
name = $('#name').val().replace(/<|>/g, ""), // prevent xss
email = $('#email').val().replace(/<|>/g, ""),
msg = $('#message').val().replace(/<|>/g, "");
if (name == '' || email == '' || msg == '') {
valid = false;
errors = "All fields are required.";
}
// pretty sure the problem is here
console.log('captcha response: ' + grecaptcha.getResponse()); // --> captcha response:
if (!errors) {
// hide the errors
$errors.slideUp();
// ajax to the php file to send the mail
$.ajax({
type: "POST",
url: "http://orenurbach.com/assets/sendmail.php",
data: "email=" + email + "&name=" + name + "&msg=" + msg + "&g-recaptcha-response=" + grecaptcha.getResponse()
}).done(function(status) {
if (status == "ok") {
// slide down the "ok" message to the user
$status.text('Thanks! Your message has been sent, and I will contact you soon.');
$status.slideDown();
// clear the form fields
$('#name').val('');
$('#email').val('');
$('#message').val('');
}
});
} else {
$errors.text(errors);
$errors.slideDown();
}
});
PHP:
<?php
// assemble the message from the POST fields
// getting the captcha
$captcha = '';
if (isset($_POST['g-recaptcha-response']))
$captcha = $_POST['g-recaptcha-response'];
echo 'captcha: '.$captcha;
if (!$captcha)
echo 'The captcha has not been checked.';
// handling the captcha and checking if it's ok
$secret = 'MY_SECRET';
$response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true);
var_dump($response);
// if the captcha is cleared with google, send the mail and echo ok.
if ($response['success'] != false) {
// send the actual mail
#mail($email_to, $subject, $finalMsg);
// the echo goes back to the ajax, so the user can know if everything is ok
echo 'ok';
} else {
echo 'not ok';
}
?>
The result in the PHP page:
captcha: The captcha has not been checked.array(2) { ["success"]=> bool(false) ["error-codes"]=> array(1) { [0]=> string(22) "missing-input-response" } } not ok
Bottom line is, how can I get the input response manually without it automatically going with the rest of the POST data?
Ok, this was pretty silly.
I have done a couple of things wrong:
In the PHP file, all the strings had single quotes on them, and that caused problems.
Throughout the testing, I added multiple printings of things in the PHP file, thus the if (status == "ok") was never working. I did get the emails but did not get any conformation that I did and now I see why.
When I wanted to check what the PHP file was omitting, I simply went to it's address in the URL and always got an error. Even when the mails were sent. Now I understand that that is not the correct way of checking the logs.
Thanks to #Samurai who helped my figure out things.
Final PHP code:
<?php
// assemble the message from the POST fields
// getting the captcha
$captcha = "";
if (isset($_POST["g-recaptcha-response"]))
$captcha = $_POST["g-recaptcha-response"];
if (!$captcha)
echo "not ok";
// handling the captcha and checking if it's ok
$secret = "MY_SECRET";
$response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$captcha."&remoteip=".$_SERVER["REMOTE_ADDR"]), true);
// if the captcha is cleared with google, send the mail and echo ok.
if ($response["success"] != false) {
// send the actual mail
#mail($email_to, $subject, $finalMsg);
// the echo goes back to the ajax, so the user can know if everything is ok
echo "ok";
} else {
echo "not ok";
}
?>
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.
I have this html markup:
<form id="ajax-contact" method="post" action="mailer.php">
<div id="form-messages"></div>
<div class="field">
<label for="name">Name:</label>
<input type="text" id="name" class="contact" name="name" placeholder="Name" required>
</div>
<div class="field">
<label for="email">Email:</label>
<input type="email" id="email" class="contact" name="email" placeholder="Email" required>
</div>
<div class="field">
<label for="message">Message:</label>
<textarea id="message" name="message" placeholder="Message" required></textarea>
</div>
<div class="field">
<button type="submit">Send</button>
</div>
</form>
this jQuery (for the AJAX call):
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
$('#message').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
and this mailer.php file:
<?php
// My modifications to mailer script from:
// http://blog.teamtreehouse.com/create-ajax-contact-form
// Added input sanitizing to prevent injection
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "email#email.com";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
The issue is that after I press the submit button, I receive this message:
Oops! An error occured and your message could not be sent.
When I check the console I see this error:
Failed to load resource: the server responded with a status of 500 (Internal Server Error) which is the mailer.php file.
However, when I check my inbox I see the email submitted in the form.
I can not figure out what is going wrong, can someone tell how can I fix this issue?
Thank you!
You are using the wrong error number - 500 is reserved for faults in code (hence why internal server error).
Even for security reasons, always send 200 however when mail returns false, log the email in a text file. Together with the get_last_error function, so that you can properly analyze your issue.
Hope this helps.
http://www.w3schools.com/php/func_error_get_last.asp