Following code:
HTML-Form Textarea:
<textarea rows="5" cols="80" id="msg"></textarea><br>
jQuery sending the form:
$.ajax({
type: "POST",
url: "source/contact.php",
data: "email=" + $("#email").val() + "&msg=" + $("#msg").val() + "&phone=" + nr,
// Display Answer
success: function(answer){
alert(unescape(answer));
$("#form_contact")[0].reset();
},
// If sending failed: Display error message
error: function(){
alert("Form Sending Fail!");
}
});
I also tried:
$("textarea#msg").val()
Then here point that out with php:
$msg = $_POST['msg'];
And it always gives TRUE back (displayed as "1")
What am I doing wrong??
EDIT: PHP-File:
<?php
if(!isset($_POST['email']) || !isset($_POST['msg']) || !isset($_POST['phone'])){
echo "Access denied!";
exit;
}
$email = htmlentities($_POST['email']);
$msg = htmlentities($_POST['msg']);
$phone = htmlentities($_POST['phone']);
if($email != "" && $msg =! "" && $phone != ""){
echo "Danke f%FCr ihre Anfrage! \n Email: $email \n Msg: $msg \n Phone: $phone";
}else{
echo "Bitte alle Fleder ausf%FCllen!";
}
?>
try this,the $msg !=
<?php
if(!isset($_POST['email']) || !isset($_POST['msg']) || !isset($_POST['phone'])){
echo "Access denied!";
exit;
}
$email = htmlentities($_POST['email']);
$msg = htmlentities($_POST['msg']);
$phone = htmlentities($_POST['phone']);
if($email != "" && $msg != "" && $phone != ""){
echo "Danke f%FCr ihre Anfrage! \n Email: $email \n Msg: $msg \n Phone: $phone";
}else{
echo "Bitte alle Fleder ausf%FCllen!";
}
?>
Related
I am trying to process a form with ajax, jquery and php and I am getting a 404 error, searched before I posted but I did not find the answer to help me fix my problem, this is the .js file :
$(document).ready(function() {
$('form #error-message').hide();
$('#submit').on('click' , function(e) {
e.preventDefault();
var valid = '';
var required = " is required";
var fname = $('form #fname').val();
var lname = $('form #fname').val();
var dbirth = $('form #dbirth').val();
var adress1 = $('form #adress1').val();
if (fname = '' || fname.lenght <= 2) {
valid += '<p><span>X</span> Full Name ' + required + '</p>';
}
if (lname = '' || lname.lenght <= 2) {
valid += '<p><span>X</span> Full Name ' + required + '</p>';
}
if (dbirth = '' || dbirth.lenght <= 2) {
valid += '<p><span>X</span> Full Name ' + required + '</p>';
}
if (adress1 = '' || adress1.lenght <= 5) {
valid += '<p><span>X</span> Full Name ' + required + '</p>';
}
if(valid != '') {
$('form #error-message').removeClass().addClass('warning')
.html('<h1>Please complete all the fields</h1>' + valid);
} else {
var contactData = $( 'form' ).serialize();
console.log(contactData);
$.ajax({
type: 'POST',
url: 'ajaxform/process.php',
data: contactData,
success: function() {
$('#error-message').removeClass().addClass('success')
.html("<h1>Thank you for contacting me. I will reply as soon as i can!</h1>");
},
error: function() {
$('#error-message').removeClass().addClass('alert-error')
.html("An error has occured. Please try again later")
},
complete: function() {
$('form')[0].reset();
}
});
}
});
});
and this is the .php file :
<?php
sleep(1);
$to = 'yourcompany#gmail.com';
$subject = 'My form contact';
if( isset($_POST['fname']) && isset($_POST['lname']) && isset($_POST['dbirth']) && isset($_POST['adress1'])) {
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$sdate = trim($_POST['dbirth']);
$adress1 = trim($_POST['adress1']);
if(!empty($fname) && !empty($lname) && !empty($dbirth) && !empty($adress1)) {
$full_name = $fname . " " . $lname;
$body = $full_name . "\n" . $adress1;
$headers = "From {$full_name} " . $dbirth;
mail($to, $subject, $body, $headers);
}
} else {
header('location: ../index.html');
}
?>
I suggest you phpmailer. You can download it at this link.
<?php
require_once('class.phpmailer.php');
sleep(1);
$to = 'yourcompany#gmail.com';
$subject = 'My form contact';
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 1; // will send erros and messages
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Host = "smtp.gmail.com";
$mail->Port = 587; //Gmail smtp port
$mail->Username = "youremail#gmail.com";
$mail->Password = "yourpassword";
$mail->SetFrom($headers);
$mail->Subject = $subject;
if( isset($_POST['fname']) && isset($_POST['lname']) && isset($_POST['dbirth']) && isset($_POST['adress1'])) {
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$sdate = trim($_POST['dbirth']);
$adress1 = trim($_POST['adress1']);
if(!empty($fname) && !empty($lname) && !empty($dbirth) && !empty($adress1)) {
$full_name = $fname . " " . $lname;
$body = $full_name . "\n" . $adress1;
$headers = "From {$full_name} " . $dbirth;
$mail->Body = $body;
$mail->AddAddress($to);
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
header('location: ../index.html');
}
}
}
?>
I'm trying to create a form with reCaptcha.
Although I'm not an expert with javascript and ajax I succeed to cretae form and verify it with ajax before submit but when I added reCaptcha to my form I couldn't verify it FrontEnd. (In Backend, it works very well and the form is sent only if all field and captcha are all correctly filled)
I want to create something to alert user when he didn't fill the reCaptcha.
Below my code:
/********** index.php *************/
<?php
$siteKey = 'public key'; // votre clé publique
?>
<form action="process.php" id="contact" method="POST">
<label for="nom" class="label-style">Nom</label>
<input class="w-input field-style" id="nom" name="nom" onkeyup="checkFilled('nom');" type="text">
<span id="msg_nom"></span>
<label for="email" class="label-style">Email</label>
<input class="w-input field-style" id="email" name="email" onkeyup="checkFilledEmail('email');" type="email">
<span id="msg_email"></span>
<label for="sujet" class="label-style" >Sujet</label>
<input class="w-input field-style" id="sujet" name="sujet" onkeyup="checkFilled('sujet');" type="text">
<span id="msg_sujet"></span>
<label class="label-style" for="message">Message</label>
<textarea class="w-input messageform" id="message" name="message" onkeyup="checkFilled('message');" rows="10" cols="80"></textarea>
<span id="msg_message"></span>
<div class="g-recaptcha" data-sitekey="<?php echo $siteKey; ?>"></div>
<span id="msg_captch"></span>
<span id="msg_all"></span>
<input class="w-button simple-button" type="submit" value="Envoyer" />
</form>
<script type="text/javascript">
function checkFilled(variable) {
var inputVal = document.getElementById(variable).value;
if (inputVal == "") {
document.getElementById(variable).style.borderColor = "red";
}
else{
document.getElementById(variable).style.borderColor = "green";
}
}
function checkFilledEmail(variable) {
fld_value = document.getElementById(variable).value;
is_m_valid = 0;
if (fld_value.indexOf('#') >= 1) {
m_valid_dom = fld_value.substr(fld_value.indexOf('#')+1).length;
if (m_valid_dom >= 1) {
is_m_valid = 1;
}
}
if (is_m_valid) {
document.getElementById(variable).style.borderColor = "green";
} else {
document.getElementById(variable).style.borderColor = "red";
}
}
$(function(){
$("#contact").submit(function(event){
var nom = $("#nom").val();
var sujet = $("#sujet").val();
var email = $("#email").val();
var message = $("#message").val();
var dataString = nom + sujet + email + message;
var captch = $('.g-recaptcha').val();
var msg_all = "Merci de remplir tous les champs";
var msg_alert = "Merci de remplir le champs: ";
var msg_captch = " merci de remplir captcha";
$("#msg_all").html('');
$("#msg_nom").html('');
$("#msg_email").html('');
$("#msg_sujet").html('');
$("#msg_message").html('');
if(dataString == "")
{
document.getElementById('nom').style.borderColor = "red";
document.getElementById('email').style.borderColor = "red";
document.getElementById('sujet').style.borderColor = "red";
document.getElementById('message').style.borderColor = "red";
$('html, body').animate({
scrollTop: $("#msg_nom").offset().top
}, 500);
}
else if(nom == "")
{
var el10=document.getElementById('nom');
el10.style.borderColor = "red";
}
else if(email == "")
{
document.getElementById('email').style.borderColor = "red";
}
else if(sujet == "")
{
document.getElementById('sujet').style.borderColor = "red";
}
else if(message == "")
{
document.getElementById('message').style.borderColor = "red";
}
else
{
$.ajax({
type : "POST",
url: $(this).attr("action"),
data: $(this).serialize(),
success : function(){
$("#msg_all").html(" <p style='text-align:center; margin-bottom:40px;'>Formulaire bien envoyé</p> ");
$(':input','#contact')
.not(':button, :submit, :reset, :hidden')
.val('');
$("#msg_nom").html('');
$("#msg_email").html('');
$("#msg_sujet").html('');
$("#msg_message").html('');
document.getElementById('nom').style.borderColor = "";
document.getElementById('email').style.borderColor = "";
document.getElementById('sujet').style.borderColor = "";
document.getElementById('message').style.borderColor = "";
$('html, body').animate({
scrollTop: $("#msg_nom").offset().top
}, 500);
},
error: function(){
$("#msg_all").html("<p style='text-align:center; margin-bottom:40px;'>Erreur dappel, le formulaire ne peut pas fonctionner</p>");
document.getElementById('nom').style.borderColor = "";
document.getElementById('email').style.borderColor = "";
document.getElementById('sujet').style.borderColor = "";
document.getElementById('message').style.borderColor = "";
}
});
}
return false;
});
});
</script>
/************ process.php **************/
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://www.google.com/recaptcha/api.js"></script>
<?php
require 'recaptchalib.php';
$secret = 'private key'; // votre clé privée
// CONDITIONS NOM
if ( (isset($_POST["nom"])) && (strlen(trim($_POST["nom"])) > 0) ):
$nom = stripslashes(strip_tags($_POST["nom"]));
else:
echo "Merci décrire un nom <br />";
$nom = "";
endif;
// CONDITIONS SUJET
if ( (isset($_POST["sujet"])) && (strlen(trim($_POST["sujet"])) > 0) ):
$sujet = stripslashes(strip_tags($_POST["sujet"]));
else:
echo "Merci décrire un sujet <br />";
$sujet = "";
endif;
// CONDITIONS EMAIL
if ( (isset($_POST["email"])) && (strlen(trim($_POST["email"])) > 0) && (filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) ):
$email = stripslashes(strip_tags($_POST["email"]));
elseif (empty($_POST["email"])):
echo "Merci décrire une adresse email <br />";
$email = "";
else:
echo "Email invalide :(<br />";
$email = "";
endif;
// CONDITIONS MESSAGE
if ( (isset($_POST["message"])) && (strlen(trim($_POST["message"])) > 0) ):
$message = stripslashes(strip_tags($_POST["message"]));
else:
echo "Merci décrire un message<br />";
$message = "";
endif;
$cap = 0;
$reCaptcha = new ReCaptcha($secret);
if(isset($_POST["g-recaptcha-response"]))
{
$resp = $reCaptcha->verifyResponse(
$_SERVER["REMOTE_ADDR"],
$_POST["g-recaptcha-response"]
);
if ($resp != null && $resp->success)
{
$cap = 1;
}
else
{
echo "verify your CAPTCHA, it is incorrect <br />";
$cap = 0;
}
}
else
{
echo "ERROR captcha <br />";
$cap = 0;
}
// Les messages d"erreurs ci-dessus s'afficheront si Javascript est désactivé
// PREPARATION DES DONNEES
$ip = $_SERVER["REMOTE_ADDR"];
$hostname = gethostbyaddr($_SERVER["REMOTE_ADDR"]);
$destinataire = 'myEmail#gmail.com';
$objet = $sujet;
$contenu = "Nom de l'expéditeur : " . $nom . "\r\n";
$contenu .= $message . "\r\n\n";
$contenu .= "Adresse IP de l'expéditeur : " . $ip . "\r\n";
$contenu .= "DLSAM : " . $hostname;
$headers = "From: " . "contact#exemple.com" . " \r\n"; // ici l"expediteur du mail
$headers .= "Reply-to: " . $email . " \r\n"; // ici l"expediteur du mail
$headers .= 'Content-Type: text/plain; charset=ISO-8859-1; DelSp=Yes; format=flowed'. "\r\n";
$headers .= 'Content-Disposition: inline' . "\r\n";
$headers .= 'Content-Transfer-Encoding: 7bit' . "\r\n";
$headers .= 'MIME-Version: 1.0';
// SI LES CHAMPS SONT MAL REMPLIS
if ( (empty($nom)) && (empty($sujet)) && (empty($email)) && (!filter_var($email, FILTER_VALIDATE_EMAIL)) && (empty($message)) ):
echo "echec";
elseif ( $cap==0 ):
echo "captcha error <br />";
// ENCAPSULATION DES DONNEES
else:
mail($destinataire,$objet,utf8_decode($contenu),$headers);
echo "Formulaire envoyé";
unset($_POST);
unset($message);
unset($sujet);
unset($email);
unset($nom);
endif;
// Les messages d"erreurs ci-dessus s"afficheront si Javascript est désactivé
?>
What I want is:
To alert user who missed to check captcha exactly like I did to verify other field before submit. I want to verify all my form before submitting ( In frontEnd). and the code above check all field in frontEnd except of captcha.
How can I verify if captcha is checked or no in frontEnd.
Any info that allow me to keep coding.
I find the solution, if We want to verify reCaptcha before submitting we have to add this simple code in submit (It will allow us to know if the reCaptcha is cheked or no):
var msg_captch = " You need to check Captcha";
var captch = jQuery('#g-recaptcha-response').val();
if(!captch)
{
$("#msg_captch").html(msg_captch);
}
Please see the code above to know what is 'msg_captch'
I need the errors on a form to show up from the submit.php onto the form page at contact.php
I have tried with Session_Start, but it is not working. This is what I have so far.
Contact.php
<?php
ob_start();
session_start();
if ($_SESSION["error"] != "") {
echo $_SESSION["error"];
$_SESSION["error"] = "";
}
?>
<?php echo $error; ?>
Submit.php
<?php
ob_start();
session_start();
?>
<?php
//fields
$link_address = 'contact'; // page to redirect to
$honeypot = '';
$error = '';
$name = 'Name';
$email = 'Email';
$comments = 'Message';
if(isset($_POST['contactus'])) {
$honeypot = $_POST['email_confirm'];
$name = $_POST['name'];
$email = $_POST['email'];
$comments = $_POST['comments'];
// honeypot
if($honeypot)
exit(1);
<?php
//error messages
if(trim($name) == 'Name') {
$error = '<div class="error_message">Need your Name</div>';
} else if(trim($name) == '') {
$error = '<div class="error_message">Need your Name</div>';
} else if(trim($email) == 'Email') {
$error = '<div class="error_message">Need your Email</div>';
} else if(trim($email) == '') {
$error = '<div class="error_message">Need your Email</div>';
} else if(!isEmail($email)) {
$error = '<div class="error_message">Need a valid email</div>';
} else if(trim($comments) == 'Message') {
$error = '<div class="error_message">A Message is required</div>';
} else if(trim($comments) == '') {
$error = '<div class="error_message">A Message is required</div>';
}
if($error == '') {
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
//email address
$address = "mail#example.com";
//email message
$e_subject = 'Web Message from: ' . $name . '.';
$e_body = "From: $name\nEmail: $email \r\n\nMessage:\n$comments\n\n\n";
$msg = $e_body . $e_content . $e_reply;
if(mail($address, $e_subject, $msg, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n"))
{
//success html page response
echo "<div id='succsess_page'>";
echo "<h1>Email Sent Successfully.</h1>";
echo "<p>Thank you. The following was sent to us. <br/><br/>$name<br/><br/>$email<br/><br/>$comments</p>";
echo "<a href='$link_address'>CLOSE THIS MESSAGE</a>";
echo "</div>";
} else echo "Error. Mail not sent";
}
}
if(!isset($_POST['contactus']) || $error != '') // Do not edit.
{
?>
<?php }
function isEmail($email) { // Email address verification, do not edit.
return(preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,12})$/",$email));
}
?>
As you can see, the $error from the inputs required should show up when the user does not enter in their $name, etc on the contact.php page where it says:
<?php echo $error; ?>
How can I have the $error(s) from the submit.php code show up on the contact.php page if a user does not fill in the required input fields?
Try this as your Submit.php added $_SESSION['error'] = $error; //if $error is not empty. Also removed extra php tag
<?php
ob_start();
session_start();
//fields
$link_address = 'contact'; // page to redirect to
$honeypot = '';
$error = '';
$name = 'Name';
$email = 'Email';
$comments = 'Message';
if(isset($_POST['contactus'])) {
$honeypot = $_POST['email_confirm'];
$name = $_POST['name'];
$email = $_POST['email'];
$comments = $_POST['comments'];
// honeypot
if($honeypot)
exit(1);
//error messages
if(trim($name) == 'Name') {
$error = '<div class="error_message">Need your Name</div>';
} else if(trim($name) == '') {
$error = '<div class="error_message">Need your Name</div>';
} else if(trim($email) == 'Email') {
$error = '<div class="error_message">Need your Email</div>';
} else if(trim($email) == '') {
$error = '<div class="error_message">Need your Email</div>';
} else if(!isEmail($email)) {
$error = '<div class="error_message">Need a valid email</div>';
} else if(trim($comments) == 'Message') {
$error = '<div class="error_message">A Message is required</div>';
} else if(trim($comments) == '') {
$error = '<div class="error_message">A Message is required</div>';
}
if (isset($error) && !empty($error)){
$_SESSION['error'] = $error; //SET errors for contact.php page to display
echo $error;
}else {
$_SESSION['error'] = '';
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
//email address
$address = "mail#example.com";
//email message
$e_subject = 'Web Message from: ' . $name . '.';
$e_body = "From: $name\nEmail: $email \r\n\nMessage:\n$comments\n\n\n";
$msg = $e_body . $e_content . $e_reply;
if(mail($address, $e_subject, $msg, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n"))
{
//success html page response
echo "<div id='succsess_page'>";
echo "<h1>Email Sent Successfully.</h1>";
echo "<p>Thank you. The following was sent to us. <br/><br/>$name<br/><br/>$email<br/><br/>$comments</p>";
echo "<a href='$link_address'>CLOSE THIS MESSAGE</a>";
echo "</div>";
} else echo "Error. Mail not sent";
}
}
if(!isset($_POST['contactus']) || $error != '') // Do not edit.
{
?>
<?php
}
function isEmail($email) { // Email address verification, do not edit.
return(preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,12})$/",$email));
}
?>
I do not understand why this ajax request is returning an error even though the error status is OK (200), any thoughts? It seems like I am missing something very obvious but I have been tearing myself apart trying to find an answer! I am new to ajax and therefore have little experience with it! Thanks for the help.
This is my ajax request:
var dataString = $('#cform').serialize();
$.ajax({
type: "POST",
url: 'contact.php',
data: dataString,
dataType: 'json',
success: function (data) {
if (data.success == 0) {
var errors = '<ul><li>';
if (data.name_msg != '')
errors += data.name_msg + '</li>';
if (data.email_msg != '')
errors += '<li>' + data.email_msg + '</li>';
if (data.godaddyemail_msg != '')
errors += '<li>' + data.godaddyemail_msg + '</li>';
if (data.godaddyuser_msg != '')
errors += '<li>' + data.godaddyuser_msg + '</li>';
$("div#output").removeClass('alert-success').addClass('alert-error').show().html('<button type="button" class="close" data-dismiss="alert">x</button><p> Could not complete your request. See the errors below!' + errors + '</p>');
}
else if (data.success == 1) {
$("div#output").removeClass('alert-error').addClass('alert-success').show().html('<button type="button" class="close" data-dismiss="alert">x</button><p>You message has been sent successfully!</p>');
}
},
error: function (error) {
$("div#output").removeClass('alert-success').addClass('alert-error').show().html('<button type="button" class="close" data-dismiss="alert">x</button><p> Could not complete your request. The Function returned an error!</p>' + error.statusText); }
});
return false;
}
This is contact.php (where the request is sent to):
<?php
$send_email_to = "My Email";
$message = 'message';
$subject = 'subject';
function send_email($name,$email,$godaddyusername,$godaddyemail)
{
global $send_email_to;
if($message=='message')$message='';
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: ".$email. "\r\n";
$message = "<strong>Email = </strong>".$email."<br>";
$message .= "<strong>Name = </strong>".$name."<br>";
$message .= "<strong>GoDaddy Username = </strong>".$godaddyusername."<br>";
$message .= "<strong>GoDaddy Email = </strong>".$godaddyemail."<br>";
mail($send_email_to, $subject, $message,$headers);
return true;
}
function validate($name,$email,$godaddyusername,$godaddyemail)
{
$return_array = array();
$return_array['success'] = '1';
$return_array['name_msg'] = '';
$return_array['email_msg'] = '';
$return_array['godaddyuser_msg'] = '';
$return_array['godaddyemail_msg'] = '';
if($email == '')
{
$return_array['success'] = '0';
$return_array['email_msg'] = 'Email is required';
}
else
{
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email)) {
$return_array['success'] = '0';
$return_array['email_msg'] = 'Enter valid emmail.';
}
}
if($name == '')
{
$return_array['success'] = '0';
$return_array['name_msg'] = 'Name is required';
}
else
{
$string_exp = "/^[A-Za-z .'-]+$/";
if (!preg_match($string_exp, $name)) {
$return_array['success'] = '0';
$return_array['name_msg'] = 'Enter valid Name.';
}
}
if($godaddyusername == '')
{
$return_array['success'] = '0';
$return_array['godaddyuser_msg'] = 'GoDaddy Username is required';
}
if($godaddyemail == '')
{
$return_array['success'] = '0';
$return_array['godaddyemail_msg'] = 'GoDaddy Email is required';
}
else
{
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$godaddyemail)) {
$return_array['success'] = '0';
$return_array['godaddyemail_msg'] = 'Enter a valid GoDaddy email.';
}
}
return $return_array;
}
$name = $_POST['name'];
$email = $_POST['email'];
$godaddyemail = $_POST['gde'];
$godaddyusername = $_POST['gdu'];
$return_array = validate($name,$email,$godaddyusername,$godaddyemail);
if($return_array['success'] == '1')
{
send_email($name,$email,$godaddyusername,$godaddyemail);
}
header('Content-type: text/json');
echo json_encode($return_array);
die();
?>
That is because you have two undefined variables on your send_email() function.
Here you have this if statement..
if($message=='message')$message=''; // $message is not available inside this function.
and here
mail($send_email_to, $subject, $message,$headers); //$subject is also undefined.
I have a simple contact form that uses js to post via php, and read the response to do some simple appending/css to list errors and a successful send. It normally pops up an error on the field if you have left it blank / if it is not a proper address, and when succesful, removes the form and appends a thank you note.
The problem is, while it works perfectly on my own server, it sends the mail without giving error/success on the production
I'm not using cross-domain requests, and I have tried disabling compression to no avail. Caching is enabled, though it should not matter.
The javascript
$('.contact-us').submit(function(e) {
e.preventDefault();
$('.contact-us input, .contact-us textarea').removeAttr('style');
$('.error').remove();
var postdata = $('.contact-us').serialize();
$.ajax({
type: 'POST',
url: 'contact2.php',
data: postdata,
dataType: 'json',
success: function(returned_data) {
var j = 0;
var submit_ok = true;
$.each(returned_data, function(key, value) {
if(value != '') {
$('.contact-us .' + key).attr('style', 'border-color: #e67632; -moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none;');
$('.contact-us .' + key).focus();
$('.contact-us').append('<div class="error"> ' + value + '</div>');
$('.error').css('top', (j*52) + 'px');
$('.error').fadeIn('slow');
submit_ok = false;
return false;
}
j++;
});
if(submit_ok) {
$('.contact-us').append('<p style="display: none;">Thanks for contacting us! We will get back to you very soon.</p>');
$('.contact-us input, .contact-us textarea, .contact-us button').remove();
$('.contact-us p').fadeIn('slow');
}
}
});
});
The php
<?php
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]* [[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $email));
}
if($_POST) {
$emailTo = 'myemail#gmail.com';
$clientName = trim($_POST['name']);
$clientEmail = trim($_POST['email']);
$subject = trim($_POST['subject']);
$message = trim($_POST['message']);
$errors_array = array('name' => '', 'email' => '', 'subject' => '', 'message' => '');
if($clientName == '') {
$errors_array['name'] = 'Please enter your name!';
}
if(!isEmail($clientEmail)) {
$errors_array['email'] = 'Insert a valid email address!';
}
if($subject == '') {
$errors_array['subject'] = 'Please enter the subject!';
}
if($message == '') {
$errors_array['message'] = 'Please enter your message!';
}
if($clientName != '' && isEmail($clientEmail) && $message != '' && $subject != '') {
// Send email
$headers = "From: " . $clientName . " <" . $clientEmail . ">" . "\r\n" . "Reply-To: " . $clientEmail;
mail($emailTo, $subject, $message, $headers);
}
echo json_encode($errors_array);
}
?>