Validating Contact Form with Captcha - javascript

I have a contact form with a captha in it. There is no problem submitting mail, but the issue I have is validation and transferring the values to submit handler. I have limited knowledge of PHP and Javascript. I humbly seek your help in checking these codes and tell me what I need to do to get it right. Any help will be appreciated!
Below are the mail handler php codes
<?php
require_once('recaptchalib.php');
$publickey = "***********";
$subject = 'CONTACT MESSAGE: ' ; //. $_REQUEST['subject']Subject of your email
$to = 'myemailaddress#domain.com'; //Recipient's E-mail
$privatekey = "***********";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if ($resp->is_valid) {
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$message .= 'Name: ' . $_REQUEST['name'] . "<br>";
$message .= 'Telephone: ' . $_REQUEST['telephone'] . "<br>";
$message .= 'Email: ' . $_REQUEST['email'] . "<br>";
$message .= 'Message: ' . $_REQUEST['message'];
if (#mail($to, $subject, $message, $headers))
{
// Transfer the value 'sent' to ajax function for showing success message.
echo 'sent';
}
else
{
// Transfer the value 'failed' to ajax function for showing error message.
echo 'failed';
}
} else {
echo "The reCAPTCHA wasn't entered correctly. Go back and try it again.".$resp->error;
}
?>
And here is the javascript
<script>
function validateForm() {
var x = document.forms["enquiries"]["name"].value;
if (x == null || x == "") {
sweetAlert("Oops...", "Please enter your full name", "error");
return false;
}
var x = document.forms["enquiries"]["email"].value;
if (x == null || x == "") {
sweetAlert("Oops...", "Please enter your a valid email address", "error");
return false;
}
var x = document.forms["enquiries"]["message"].value;
if (x == null || x == "") {
sweetAlert("Oops...", "Please enter your the message you wish to send", "error");
return false;
}
// If there is no validation error, next to process the mail function
if(error == false){
/* Post Ajax function of jQuery to get all the data from the submission of the form as soon as the form sends the values to email.php*/
$.post("processContactEmail.php", $("#enquiries").serialize(),function(result){
//Check the result set from email.php file.
if(result == 'sent'){
sweetAlert("Congratulations", "Your message has been sent successfully!", "success");
}else{
//Display the error message
}
});
}
}
</script>
and finally, the html
<form name="enquiries" id='enquiries' method="post" action='processContactEmail.php' onSubmit="return validate();">
<label> <input name="name" type="text" id="name" style="width: 90%;" placeholder="Name" ></label>
<label><input name="email" type="text" id="email" style="width: 90%;" placeholder="Email"></label>
<label><textarea name="message" id="message" style="width: 96.5%;" class="mssg" rows="10" placeholder="Message"></textarea>
</label>
<label><?php echo recaptcha_get_html($publickey) ?></label>
<label><input name="submit" type='submit' id='mssg_buttton' value='Send Message'></label>
</form>
When I clicked on the submit button, I was taken straight to
processContactEmail.php page without the form validating
How do I display this error: echo "The reCAPTCHA wasn't entered correctly. Go back and try it again.".$resp->error; in my alert
I'm not sure about this line if(error == false){ in the JS script since there is no variable declared

The first problem looks like your validation function is referred to in your HTML as validate();
<form name="enquiries" id='enquiries' method="post" action='processContactEmail.php' onSubmit="return validate();">
But in your Javascript the function defined is called validateForm(). To fix that just make sure these are called the same thing (doesn't matter what, as long as they match).
Rather than calling the validation function inline with onSubmit="return validate();" , it's better to attach a separate event listener in the Javascript. It's good practice to separate your HTML and Javascript code. I see you're using JQuery, so you do this in your Javascript like so:
$( document ).ready(function() { // Make sure DOM is loaded before attaching the event listener to the form element
$("#enquiries").on("submit", validateForm); // Add submit listener to the form with the id 'enquiries' and run the function called validateForm on submit
});
Secondly, in your validate function, you need to prevent the form's default action of submitting and redirecting to the action processContactEmail.php. The HTML form will always try to post to its default action, so do make it do something else (like validate) you must actively stop it from posting.
You do this in JQuery by editing your validateForm function to prevent the form's default action with event.preventDefault. As for the error, you must first set an error variable to false (assume all is fine) and as you find errors, you change it to true. If it's still false after the checks, there were no errors.
Your Javascript function should look like this:
function validateForm(event) {
event.preventDefault(); // the variable "event" is automatically included in the submit event listener.
var error = false; // Assume it's fine unless proven otherwise
var x = document.forms["enquiries"]["name"].value;
if (x == null || x == "") {
sweetAlert("Oops...", "Please enter your full name", "error");
error = true; // The form is not fine. Set error to true.
// No return, or you will not get to the rest of your function
}
var x = document.forms["enquiries"]["email"].value;
if (x == null || x == "") {
sweetAlert("Oops...", "Please enter your a valid email address", "error");
error = true; // The form is not fine. Set error to true.
}
var x = document.forms["enquiries"]["message"].value;
if (x == null || x == "") {
sweetAlert("Oops...", "Please enter your the message you wish to send", "error");
error = true; // The form is not fine. Set error to true.
}
// If there is no validation error, next to process the mail function
if(error == false){ // error was never set to true, so it must still be false and the form is OK.
/* Post Ajax function of jQuery to get all the data from the submission of the form as soon as the form sends the values to email.php */
$.post("processContactEmail.php", $("#enquiries").serialize(),function(result){
//Check the result set from email.php file.
if(result == 'sent'){
sweetAlert("Congratulations", "Your message has been sent successfully!", "success");
} else {
//Display the error message
}
});
}
}
After these changes, your form will not post to its action, and your validateForm function should run, check for the errors, and if there are none, make the ajax POST to processContactEmail.php.

Related

Uncaught ReferenceError: ajaxObj is not defined

Uncaught ReferenceError: ajaxObj is not definednewsletter #
main.js:22onclick # index.php:541
I am trying to develop a newsletter which will be on the footer part of the every page and it will use NAME and EMAIL to suscribe. It will grab the data entered by user from HTML form and pass it to ajax for validation after usere click submit which will pass information to newsletter.php and give back message to user if they already exist or signup sucessfull message but what happened is as User click submit button it just says "Please wait.." and keeps on loading forever giving above message on chrome cousole.
I want user to be able to sign up from any page they are on without reloading page.
The problem here is
Above Error given in Chrome cousole while I try to submit the form.
Thank you for looking at my problem. Any help will be appriciated..
HTML
<?php include_once('newsletter.php'); ?>
<form name="signupform" id="signupform" method="POST" onsubmit="return false;">
<p align="center"><strong>NEWSLETTER SIGNUP :</strong>
<input id="sus_name" name="sus_name" type="text" placeholder="Enter your Name" size="15">
<input id="sus_email" name="sus_email" type="text" placeholder="Enter your Email" size="26">
<input id="optin" name="optin" type="submit" value="SUBSCRIBE" onclick="newsletter()"><br>
<span id="status"></span>
</p>
</form>
AJAX
//News Letter Validation
function newsletter(){
var u = document.getElementById("sus_name").value;
var e = document.getElementById("sus_email").value;
var m =(document.URL);
var status = document.getElementById("status");
if(u == "" || e == ""){
status.innerHTML = "Fill out all of the form data";
} else {
document.getElementById("optin").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST","(document.URL)");//Problem with this line as i want it to post to same page where url will be dynamic
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
document.getElementById("optin").style.display = "block";
} else {
window.scrollTo(0,0);
document.getElementById("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> ";
}
}
}
ajax.send("u="+u+"&e="+e);
}
}
newsletter.php
<?php
$msg_to_user = "";
if(isset($_POST["u"])){
// CONNECT TO THE DATABASE
include_once "includes/mysqli_connect.php";
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$u = ereg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$e = mysql_real_escape_string($_POST['e']);
// GET USER IP ADDRESS
$ip = ereg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
if (($u != "") && ($e != "") ){
// Be sure to filter this data to deter SQL injection, filter before querying database
$name = $u;
$email = $e;
$sql = mysql_query("SELECT * FROM news_letter WHERE susc_email='$email'");
$numRows = mysql_num_rows($sql);
if (!$email) {
$msg_to_user = '<br /><br /><h4><font color="#FFFFFF">Please type an email address ' . $name . '.</font></h4>';
} else if ($numRows > 0) {
$msg_to_user = '<br /><br /><h4><font color="#FFFFFF">' . $email . ' is already in the system.</font></h4>';
} else {
$i= substr($name,0,3);
$j=rand(1000,9999);
$l= substr($email,0,3);
$k= $i.$j.$l;
$o=rand(0,9);
$m=str_replace("#","$o","$k");
$n=mysql_real_escape_string($m);
$sql_insert = mysql_query("INSERT INTO news_letter (susc_name, susc_email, susc_date, susc_code)
VALUES('$name','$email',now(),'$n')") or die (mysql_error());
$msg_to_user = '<br /><br /><h4><font color="#FFFFFF">Thanks ' . $name . ', you have been added successfully.</font></h4>';
echo "signup_success";
exit();
}
}
}
?>

ReCaptcha 2.0 With AJAX

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";
}
?>

showing text in div without reloading the page

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/

Pop up form does not send email

I have problem with pop up form . It doesn't send email. Here is html form:
<form action="#" method="post" id="form" >
<img src="images/3.png" id="close"/>
<h2>Contact Us</h2><hr/>
<input type="text" name="name" id="name" placeholder="Name"/>
<input type="text" name="email" id="email" placeholder="Email"/>
<textarea name="message" placeholder="Message" id="msg"></textarea>
<a id="submit" href="javascript: check_empty()">Send</a>
</form>
JS to pop up html form:
function check_empty(){
if(document.getElementById('name').value == ""
|| document.getElementById('email').value == ""
||document.getElementById('msg').value == "" ){
alert ("Fill All Fields !");
}
else {
document.getElementById('form').submit();
alert ("Form submitted successfully...");
}
}
//function to display Popup
function div_show(){
document.getElementById('abc').style.display = "block";
}
//function to check target element
function check(e){
var target = (e && e.target) || (event && event.srcElement);
var obj = document.getElementById('abc');
var obj2 = document.getElementById('popup');
checkParent(target)?obj.style.display='none':null;
target==obj2?obj.style.display='block':null;
}
//function to check parent node and return result accordingly
function checkParent(t){
while(t.parentNode){
if(t==document.getElementById('abc'))
{
return false
}
else if(t==document.getElementById('close'))
{
return true
}
t=t.parentNode
}
return true
}
And php function to send form data to email. Everything work but i don't receive email on gmail. Similar php script i used to post email without pop up and it worked.
<?php
if(isset($_POST['submit'])){
$to = "myemail#gmail.com";
$from = $_POST['email'];
$first_name = $_POST['name'];
$message = $first_name . " wrote following:" . "\n\n" . $_POST['message'];
mail($to,$from,$message);
}
?>
Simple: You don't have an element named "submit" in your form, so your if() test always fails.
id != name in HTML forms; meaning, id does not equal name.
A simple work around:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... form was submitted ...
}
But this code is bad in any case. You should NEVER use only client-side validation. It's too easy to bypass. ALWAYS validate/verify on the server as well.
You should set your action in the form to the URL of your action in the server.

Different function for form success and for the form validation messages

I've just been helped with some functions and callbacks to get this animation on my form once submitted:
$("#message").show().delay(5000).fadeOut('fast', function(){
$("#slide_panel").slideToggle("slow");
});
Though, the problem I have now is, if someone had to submit the form without entering the correct details, the error message will also pop up (pops up in the same div "message" as the thank you message), delays for 5 seconds and then closes the form.
Of course, I don't want it to close the form, instead show the error message for 5 seconds and then fadeout the error message.
Anything I need to add here:
function(data){
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#contactform img.loader').fadeOut('fast',function()
{$(this).remove()});
$('#submit').removeAttr('disabled');
if(data.match('success') != null);
$('#name').val( "" );
$('#email').val( "" );
$('#phone').val( "" );
$('#dayin').val( "" );
$('#dayout').val( "" );
$('#comments').val( "" );
$('#verify').val( "" );
$("#message").show().delay(5000).fadeOut('fast',
function(){
$("#slide_panel").slideToggle("slow");
});
}
);
});
return false;
});
});
I'm assuming I need to do something similar to this code:
if(data.match('success') != null);
In my contact.php form.... I have this:
if (isset($_POST['verify'])) :
$posted_verify = $_POST['verify'];
$posted_verify = md5($posted_verify);
else :
$posted_verify = '';
endif;
// Important Variables
$session_verify = $_SESSION['verify'];
if (empty($session_verify)) $session_verify = $_COOKIE['verify'];
$error = '';
if(trim($name) == '') {
$error .= '<li>Your name is required.</li>';
}
if(trim($email) == '') {
$error .= '<li>Your e-mail address is required.</li>';
} elseif(!isEmail($email)) {
$error .= '<li>You have entered an invalid e-mail address.</li>';
}
if(trim($phone) == '') {
$error .= '<li>Your phone number is required.</li>';
} elseif(!is_numeric($phone)) {
$error .= '<li>Your phone number can only contain digits.</li>';
}
if(trim($comments) == '') {
$error .= '<li>You must enter a message to send.</li>';
}
if($session_verify != $posted_verify) {
$error .= '<li>The verification code you entered is incorrect.
</li>';
}
if($error != '') {
echo '<div class="error_message">Attention! Please correct the
errors below and try again.';
echo '<ul class="error_messages">' . $error . '</ul>';
echo '</div>';
} else {
if(get_magic_quotes_gpc()) { $comments = stripslashes($comments); }
Anything I need to do here? Or do I only need to edit the javascript file?
if you use JSON to call a function somewhere in the code behind you will be able to return a status property.
I used it aswell in my current project and here is an example of how I used it:
var link = '/brainbattleJSON/MarkAssignmentAsInProgress';
$(this).hide();
$.getJSON(link, { questionId: qId }, function (json) {
if(json.status == "ok"){
//do this
}else{
//do this
}
});
Code behind:
// your function with validation
// if the form is valid make status "ok" otherwise put anything else
Return Json(New With {.status = "ok"});
I hope this can help you a bit :)
Edit:
You will need to change the value of var link to the path of your function where you check the form.
Then where you now say if your error!='' you will send back the json.
in this you will say:
return json(new with{.status = 'error', .errors = 'yourErrors'})
So for errors it might be useful to send an array just in case if you get more than 1 error on the form.
All the messages will no longer be shown in php with echo but you will have to put the errors there with javascript.
I have a uploaded register and login pages(zip file) at following link:
http://www.4shared.com/folder/uanQHCAg/_online.html
It uses same div to display success and error messages. You can try and implement what you are looking for, with an addition of fadeout effect.

Categories

Resources