i was messing around many hours with my custom form for a wordpress website and i cant figure it out how to properly connect ajax to my contact.php, here is my code! I appreciate any help! Thank you!
HTML
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/ajax_submit.js"></script>
<form id="feedback" action="<?php bloginfo('template_url'); ?>/contact.php" enctype="multipart/form-data" method="post">
<div id="response" class="success" style="display:none;"></div>
<div class="inputs">
<input name="name" type="text" class="required" id="name" placeholder="Имя">
</div>
<div class="inputs">
<input name="email" type="text" class="required" id="email" placeholder="Электронная почта">
</div>
<div class="inputs">
<textarea name="message" class="required" id="message" placeholder="О чём бы Вы с нами хотели поговорить?"></textarea>
</div>
<div class="button">
<input type="submit" name="submit" id="submit" value="Submit" />
</div>
<div class="inputs">
<input type="hidden" name="honeypot" id="honeypot" value="http://" />
<input type="hidden" name="humancheck" id="humancheck" class="clear" value="" />
</div>
</form>
Ajax
$(document).ready(function() {
$('form #response').hide();
$('#submit').click(function(e) {
// prevent forms default action until
// error check has been performed
e.preventDefault();
// grab form field values
var valid = '';
var required = ' is required.';
var name = $('form #name').val();
var email = $('form #email').val();
var message = $('form #message').val();
var honeypot = $('form #honeypot').val();
var humancheck = $('form #humancheck').val();
// perform error checking
if (name = '' || name.length <= 2) {
valid = '<p>Your name' + required +'</p>';
}
if (!email.match(/^([a-z0-9._-]+#[a-z0-9._-]+\.[a-z]{2,4}$)/i)) {
valid += '<p>Your email' + required +'</p>';
}
if (message = '' || message.length <= 5) {
valid += '<p>A message' + required + '</p>';
}
if (honeypot != 'http://') {
valid += '<p>Spambots are not allowed.</p>';
}
if (humancheck != '') {
valid += '<p>A human user' + required + '</p>';
}
// let the user know if there are erros with the form
if (valid != '') {
$('form #response').removeClass().addClass('error')
.html('<strong>Please correct the errors below.</strong>' +valid).fadeIn('fast');
}
// let the user know something is happening behind the scenes
// serialize the form data and send to our ajax function
else {
$('form #response').removeClass().addClass('processing').html('Processing...').fadeIn('fast');
var formData = $('form').serialize();
submitForm(formData);
}
});
});
// make our ajax request to the server
function submitForm(formData) {
jQuery.ajax({
type: 'POST',
url: 'contact.php',
data: formData,
dataType: 'json',
cache: false,
timeout: 7000,
success: function (data) {
$('form #response').removeClass().addClass((data.error === true) ? 'error' : 'success')
.html(data.msg).fadeIn('fast');
if ($('form #response').hasClass('success')) {
setTimeout("$('form #response').fadeOut('fast')", 5000);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('form #response').removeClass().addClass('error')
.html('<p>There was an<strong> ' + errorThrown +
'</strong> error due to a<strong> ' + textStatus +
'</strong> condition.</p>').fadeIn('fast');
},
complete: function(XMLHttpRequest, status) {
$('form')[0].reset();
}
});
};
PHP
function getEmail(){
sleep(3);
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$message = trim($_POST['message']);
$honeypot = $_POST['honeypot'];
$huancheck = $_POST['humancheck'];
if ($honeypot == 'http://' && empty($humancheck)) {
$error_message = '';
$reg_exp = "/^[a-zA-Z0-9._%+-]+#[a-zA-Z0-9-]+\.[a-zA-Z.]{2,4}$/";
if (!preg_match($reg_exp, $email)) {
$error_message .= "<p> A valid email is required</p>";
}
if (empty($name)) {
$error_message .= "<p>Please provide your name</p>";
}
if (empty($message)) {
$error_message .= "<p>A message is required.</p>";
}
if (!empty($error_message)) {
$return['error'] = true;
$return['msg'] = "<h3>Oops! The request was successful but your form is not filled out correctly.</h3>".$error_message;
echo json_encode($return);
exit();
} else {
$to = 'kaijin2010#gmail.com';
$headers = 'RNO-Version: 1.0' . '\n';
$headers .= 'From: $from' . '\n';
$subject = 'Contact Form Submission\n';
$body = 'Name: ' .$name . '\n';
$body .= 'Email: ' . $email . '\n';
$body .= 'Message: ' .$message . '\n';
}
} else {
$return['error'] = true;
$return['msg'] = "<h3>Oops! There was a problem with your submission. Please try again.</h3>";
echo json_encode($return);
}
}
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 have a pretty basic form that uses php to send an email and do some basic validation. It's also using ajax so the page doesn't have to reload on submission. The form's been working well, but if someone submits the form and it fails validation, all form fields are reset.
How would I go about keeping the values a user has entered when the form fails? I have a feeling it'll have something to do with my javascript file, but I'm a newb with javascript and not really sure what direction to go. Can anyone help?
Here's my form.html:
<div id="response"></div>
<div class="form-group">
<label for="name">Your Name:</label>
<input type="text" name="name" id="name" class="form-control" placeholder="Jesse James">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" name="email" id="email" class="form-control" placeholder="howCan#weReachYou.com">
</div>
<div class="form-group">
<label for="phone">Phone:</label>
<input type="tel" name="phone" id="phone" class="form-control" placeholder="734-968-4509">
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" id="message" name="message" rows="6" placeholder="How can we help...?"></textarea>
</div>
<button type="submit" name="submit" id="submit" class="btn btn-default">Send It</button>
<input type="hidden" name="honeypot" id="honeypot" value="http://">
<input type="hidden" name="humancheck" id="humanCheck" class="clear" value="">
and the ajax_sumit.js:
$(document).ready(function() {
$('#contact input:submit').click(function() {
$('#contact form').attr('action', 'http://' + document.domain + '/php/feedback.php');
$('#contact form').submit();
});
$('form #response').hide();
$('form #nameResponse').hide();
$('form #phoneResponse').hide();
$('form #emailResponse').hide();
$('form #messageResponse').hide();
$('#submit').click(function(e) {
// prevent forms default action until
// error check has been performed
e.preventDefault();
// grab form field values
var valid = '';
var nameResponse = '';
var phoneReponse = '';
var emailResponse = '';
var messageResponse = '';
var required = ' is required.';
var name = $('form #name').val();
var phone = $('form #phone').val();
var email = $('form #email').val();
var message = $('form #message').val();
var honeypot = $('form #honeypot').val();
var humanCheck = $('form #humanCheck').val();
// perform error checking
if (name = '' || name.length <= 2) {
nameResponse = '<p>Your name' + required +'</p>';
}
if (phone ) {
}
if (!email.match(/^([a-z0-9._-]+#[a-z0-9._-]+\.[a-z]{2,4}$)/i)) {
emailResponse += '<p>Your email' + required +'</p>';
}
if (message = '' || message.length <= 5) {
messageResponse += '<p>A message' + required + '</p>';
}
if (honeypot != 'http://') {
valid += '<p>Spambots are not allowed.</p>';
}
if (humanCheck != '') {
valid += '<p>A human user' + required + '</p>';
}
// let the user know if there are erros with the form
if (valid != '') {
$('form #response').removeClass().addClass('error')
.html('<div class="alert alert-danger">'+
'<strong>Please correct the errors below.</strong>' + '</div>'
).fadeIn('fast');
if (nameResponse != '') {
$('form #nameResponse').removeClass().addClass('error')
.html('<div class="alert alert-danger">'+
nameResponse + '</div>'
).fadeIn('fast');
}
if (phoneResponse != '') {
$('form #nameResponse').removeClass().addClass('error')
.html('<div class="alert alert-danger">'+
phoneResponse + '</div>'
).fadeIn('fast');
}
if (emailResponse != '') {
$('form #nameResponse').removeClass().addClass('error')
.html('<div class="alert alert-danger">'+
emailResponse + '</div>'
).fadeIn('fast');
}
if (messageResponse != '') {
$('form #nameResponse').removeClass().addClass('error')
.html('<div class="alert alert-danger">'+
messageResponse + '</div>'
).fadeIn('fast');
}
}
// let the user know something is happening behind the scenes
// serialize the form data and send to our ajax function
else {
$('form #response').removeClass().addClass('processing').html('Processing...').fadeIn('fast');
var formData = $('form').serialize();
submitForm(formData);
}
});
});
function submitForm(formData) {
$.ajax({
type: 'POST',
url: 'php/feedback.php',
data: formData,
dataType: 'json',
cache: false,
timeout: 7000,
success:
function(data) {
//we are getting data.error (from ajax, which is formData) and data.msg from our feedback.php
$('form #response').removeClass().addClass((data.error === true) ? 'error':'success')
.html(data.msg).fadeIn('fast');
if ($('form #response').hasClass('success')) {
setTimeout ("$('form #response').fadeOut('fast')",5000);
}
},
error:
function (XMLHttpRequest, textStatus, errorThrown) {
$('form #response').removeClass().addClass('error')
.html('<div class="alert alert-danger">' +
'<p>There was an <strong>' + errorThrown +
'</strong> error due to a <strong>' + textStatus +
'</strong> condition.</p>' +
'</div>').fadeIn('fast');
},
complete: function(XMLHttpRequest, status) {
$('form') [0].reset();
}
});
};
And the feedback.php:
<?php
sleep(.5);
//Sanitize incoming data and store in variable
$name = trim(stripslashes(htmlspecialchars($_POST['name'])));
$email = trim(stripslashes(htmlspecialchars($_POST['email'])));
$phone = trim(stripslashes(htmlspecialchars($_POST['phone'])));
$phoneLink = preg_replace('/\D+/', '', $phone);
$message = trim(stripslashes(htmlspecialchars($_POST['message'])));
$humancheck = $_POST['humancheck'];
$honeypot = $_POST['honeypot'];
if ($honeypot == 'http://' && empty($humancheck)) {
//Validate data and return success or error message
$error_message = '';
$reg_exp = "/^[a-zA-Z0-9._%+-]+#[a-zA-Z0-9-]+\.[a-zA-Z.]{2,4}$/";
if (!preg_match($reg_exp, $email)) {
$error_message .= "<p>A valid email address is required.</p>";
}
if (empty($name)) {
$error_message .= "<p>Please provide your name.</p>";
}
if (empty($message)) {
$error_message .= "<p>A message is required.</p>";
}
if (!empty($error_message)) {
$return['error'] = true;
$return['msg'] = '<div class="alert alert-danger">'."<h3>Oops! The request was successful but your form is not filled out correctly.</h3>".$error_message;
echo json_encode($return);
exit();
}
else {
//mail variables
#$to = 'Mainstwebguy#gmail.com';
$to = 'Jason#mainstreetcomp.com';
$from = $_POST['email'];
$headers = 'From: '.$from."\r\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$subject = "Contact Form Submission\n";
$body = '<p>Name: '.$name."</p>";
$body .= '<p>Email: '."".$email.""."</p>";
if(isset ($phone) && $phone != '') {
$body .= '<p>Phone: '.'<a href="tel:+1'.$phoneLink.'"'.$phone.'>'.$phone."</a>";
}
$body .= '<p>Message: '.$message."</p>";
//send email and return a message to user
if(mail($to, $subject, $body, $headers)) {
$return['error'] = false;
$return['msg'] =
'<div class="alert alert-success">'.
"<h3>Thanks for your feedback " .$name ."</h3>".
"<p>We'll reply to you at ".$email." as soon as we can.</p>";
echo json_encode($return);
}
else {
$return['error'] = true;
$return['msg'] = "<h3>Oops! There was a problem sending the email. Please try again.</h3>";
echo json_encode($return);
}
}
}
else {
$return['error'] = true;
$return['msg'] = "<h3>Oops! There was a problem with your submission. Please try again.</h3>";
echo json_encode($return);
}
?>
I really appreciate any help! :-)
I think the easiest way is to store the values in a session and destroy that after processing.
this resource might help: Storing Form Data as a Session Variable
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 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);
}
?>