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'
Related
I am trying to upload an Image of a Form via FTP.
But because I validate my Form with Javascript I can't offer PHP the File Object.
Instead I pass the temporary blob path of the image.
When I try to upload, it doesn't work.
If I take then the blob path and put it manually in the brwoser line it displayes the image which means my blob path isn't corrupt.
Can't PHP / FTP take an blob temp image as the source file?
Here is my Code:
Javascript and HTML
$(document).ready(function() {
$('#testImageSelect').change( function(event) {
var validation = false;
var message = "";
validation = validateImage();
if(validation){
message = "Javascript: Das Bild ist ok!";
$("#submitTest").attr("disabled",false);
}else{
message = "Javascript: Das Bild entspricht nicht den Anforderungen!";
$("#submitTest").attr("disabled",true);
}
document.getElementById("scriptresultJs").innerHTML = "<p>"+message+"</p>";
});
$("#submitTest").click(function () {
var message = "";
var dataSubmit = [];
var pic = document.getElementById("testImageSelect").files[0];
var pic_path = URL.createObjectURL(pic);
var picture = [];
picture = {
tmp_path: pic_path,
name: pic.name,
size: pic.size
}
dataSubmit = {
castingcity: "Coruscant",
forename: "Anakin",
lastname: "Skywalker",
geschlecht: "Männlich"
};
var result = "default";
result = $.ajax({
type: 'POST',
async: false, // WICHTIG!
url: 'http://hiddentalents.de/php/test.php',
data: ({
data: dataSubmit,
picture: picture
})
}).responseText;
message = result;
document.getElementById("scriptresultPHP").innerHTML = "<p>"+message+"</p>";
});
});
function validateImage() {
var validation = false;
var pic = $("#testImageSelect").val().split('/').pop().split('\\').pop();
var ext = pic.substring(pic.lastIndexOf('.') + 1);
if(ext == "JPEG" || ext == "jpeg" || ext == "jpg" || ext == "JPG"){
validation = true;
}
else{
validation = false;
}
return validation;
}
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="screen">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<title>Servertesting</title>
</head>
<body>
<form role="form" method="post" action="" id="testForm" enctype="multipart/form-data">
<input type="file" id="testImageSelect" name="testImageSelect" required>
</form>
<button class="btn btn-default" id="submitTest" disabled>Abschicken</button>
<div id="scriptresultJs"></div>
<p id="scriptresultPHP"></p>
</body>
</html>
PHP
<?php
$db_host = "rdbms.strato.de";
$db_datenbank = "(name of database)";
$db_username = "(username)";
$db_password = "(password)";
$output = "";
SESSION_START();
# Datenbankverbindung herstellen
$datenbank = new mysqli($db_host, $db_username, $db_password, $db_datenbank);
# Hat die Verbindung geklappt ?
if ($datenbank->connect_errno) {
$output = $output . "\n" . "Fehler beim Verbinden mit der Datenbank: (" . $datenbank->connect_errno . ") " . $datenbank->connect_error;
}
//UTF 8 einstellen
mysqli_query($datenbank, "SET NAMES 'utf8'");
# Wurde überhaupt was eingetragen?
if(isset($_POST["data"])) {
//Image überprüfung:
$output = $output . "\n". $_POST["picture"]["tmp_path"];
$target_dir = "temp/";
$target_file_path = $target_dir . date('dmYHis_') . $_POST["picture"]["name"];
$uploadOk = 1;
$imageFileType = pathinfo($target_file_path,PATHINFO_EXTENSION);
// Check if file already exists
if (file_exists($target_file_path)) {
$output = $output . "\n" . "Es tut uns leid, das gewählte Bild existiert bereits.";
$uploadOk = 0;
}
// Check file size
if ($_POST["picture"]["size"] > 1500000) {
$output = $output . "\n" . "Die Bilddatei ist leider zu groß.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "jpeg" && $imageFileType != "JPG" && $imageFileType != "JPEG" ) {
$output = $output . "\n" . "Leider sind nur JPG bzw. JPEG Dateien erlaubt. Sie haben eine " . $imageFileType . " Datei hochgeladen!";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
$output = "Die Datei konnte leider nicht hochgeladen werden. Folgende Fehler sind verantwortlich:\n".$output;
// if everything is ok, try to upload file
} else {
//Upload Image
$ftp_server = "ftp.strato.de";
$ftp_user_name = "(username)";
$ftp_user_pass = "(password)";
$destination_file = $target_file_path;
$source_file = $_POST['picture']["temp_path"];
// Verbindung aufbauen
$conn_id = ftp_connect($ftp_server);
// Login mit Benutzername und Passwort
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// Verbindung überprüfen
if ((!$conn_id) || (!$login_result)) {
$output = $output . "\n" . "FTP-Verbindung ist fehlgeschlagen!";
$output = $output . "\n" . "Verbindungsaufbau zu $ftp_server mit Benutzername $ftp_user_name versucht.";
exit;
} else {
$output = $output . "\n" . "Verbunden zu $ftp_server mit Benutzername $ftp_user_name";
}
// Datei hochladen
$upload = ftp_put($conn_id, $destination_file, $source_file, FTP_BINARY);
// Upload überprüfen
if (!$upload) {
$output = $output . "\n" . "FTP-Upload ist fehlgeschlagen!\nDie Datei $source_file konnte nicht auf dem Server $ftp_server als $destination_file hochgeladen werden!";
} else {
$output = $output . "\n" . "Datei $source_file auf Server $ftp_server als $destination_file hochgeladen";
}
// Verbindung schließen
ftp_close($conn_id);
//Datenbankeinträge machen:
$castingcity = mysqli_real_escape_string($datenbank,$_POST["data"]["castingcity"]);
$forename = mysqli_real_escape_string($datenbank,$_POST["data"]["forename"]);
$lastname = mysqli_real_escape_string($datenbank,$_POST["data"]["lastname"]);
$geschlecht = mysqli_real_escape_string($datenbank,$_POST["data"]["geschlecht"]);
$picture = $target_file_path;
//Insert Data (except Image)
$sql = "INSERT INTO candidates_temp (castingcity, forename, lastname, geschlecht, picture)
VALUES ('$castingcity', '$forename', '$lastname', '$geschlecht', '$picture')";
if ($datenbank->query($sql) === TRUE) {
$output = $output . "\n" . "Datenbank Werte eingetragen!";
} else {
$output = $output . "\n" . "Error: " . $sql . "<br>" . $datenbank->error;
}
}
}else {
$output = $output . "\n" . "POST Variable leer!";
}
$datenbank->close();
echo $output;
?>
Finally solved
If ound this Tutorial, and it works!!!
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 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 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);
}
}
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!";
}
?>