Cant get google recaptcha v2 to prevent form submission - php

So I can successfully get the captcha to validate, using the following code.
</p>
<?php
if(isset($_POST['g-recaptcha-response'])){
echo verify($_POST['g-recaptcha-response']);
}
function verify($response) {
$ip = $_SERVER['blank']; //server Ip
$key="secretkey"; // Secret key
//Build up the url
$url = 'https://www.google.com/recaptcha/api/siteverify';
$full_url = $url.'?secret='.$key.'&response='.$response.'&remoteip='.$ip;
//Get the response back decode the json
$data = json_decode(file_get_contents($full_url));
//Return true or false, based on users input
if(isset($data->success) && $data->success == true) {
return True;
}
return False;
}
?>
<p style="text-align: justify;">
<script type="text/javascript">
function verify(){
var serializedValues = jQuery("#infoForm").serialize();
jQuery.ajax({ type: 'POST',url:"verify.php",data: serializedValues,success:function(result){
if(result){
$('#show').html('Your Form Successfully Submitted');
$('.formwrap').hide(result);
return true;
}
}});
$('#show').html('Please Enter Valid Captcha');
return false;
}
var onloadCallback = function() {
grecaptcha.render('captcha_ele', {
'sitekey' : 'Enter Your Site Key Here', // Site key
});
};
</script>
However, when I click submit, regardless of what the captcha says, form will still submit. My email form process is as follows...
<!-- language: lang-css -->
$("#blank").submit(function() {
$.post('assets/php/email-process.php', {name: $('#name').val(), email: $('#email').val(), message: $('#message').val(), myFormSubmitted: 'yes'},
function(data) {
$("#formResponse").html(data).fadeIn('100');
$('#name, #email, #message').val(''); /* Clear the inputs */
}, 'text');
return false;
});
<?php
if ($_POST['leaveblank'] != '' or $_POST['dontchange'] != 'http://') {
// display message that the form submission was rejected
}
else {
// accept form submission
$to = 'info#blank'; // Replace with your email
$subject = 'Message from website visitor'; // Replace with your $subject
$headers = 'From: ' . $_POST['email'] . "\r\n" . 'Reply-To: ' . $_POST['email'];
$message = 'Name: ' . $_POST['name'] . "\n" .
'E-mail: ' . $_POST['email'] . "\n" .
'Subject: ' . $_POST['subject'] . "\n" .
'Message: ' . $_POST['message'];
mail($to, $subject, $message, $headers);
if( $_POST['copy'] == 'on' )
{
mail($_POST['email'], $subject, $message, $headers);
}
echo 'Thank you for your Email. We will get in touch with you very soon.';
}
?>

I use this which works for me. Put a js function in your form submit to validate the re-captcha:
<form action="/sign-visitors-log/" method="post" id="VisitorsLogForm" onsubmit="return validateRecaptcha();">
Then some js to stop the form submit if the user didn't tick the check box:
function validateRecaptcha() {
var response = grecaptcha.getResponse();
if (response.length === 0) {
alert("not validated");
return false;
} else {
alert("validated");
return true;
}
}
You can swap out the alerts for toast or as you are doing some elements on the page.
HTH

In a separate js file (at least: no inline call to a function), you have to check if the captcha can validate. Like so:
jquery('form').on('submit',function(e){
if(grecaptcha.getResponse() === "") {
e.preventDefault();
alert('Error: \n please validate the Captcha test');
}
});
You don't have to check if the test passive as true, you have already prevented the form to be sent with this method.

This is a simpler model that does the job
document.querySelector(".form").addEventListener("submit", (event)=>{
const response = grecaptcha.getResponse();
if (response.length === 0) {
event.preventDefault();
alert("Please verify that you are human!");
}
})
<!--reCAPTCHA v2 -->
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<form action="/" method="POST" class"form">
<!--Please register as a developer and add "your_site_key" you will find it on https://www.google.com/recaptcha/admin/create-->
<div class="g-recaptcha" data-sitekey="your_site_key"></div>
</form>

Related

File attachments fails

Hi I am trying to send a mail with phpmailer lib, with option to attach multiple files.
But my mailer script doesnt send mails.
I have used a similar script to send mails successfully. But it fails when I try with attachments. I followed the PHPmailer example.
(I am using recaptcha 3 with this form.)
If possible, kindly take a look and let me know what I might be doing wrong.
Thanks a lot in advance.
The html file
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Multiple File Upload</title>
</head>
<body>
<form method="post" id="contact-form" enctype="multipart/form-data" action="testmailer.php">
<input name="fname" placeholder="Your name" title="Your name" type="text" /></div>
Select one or more files:
<input name="userfile[]" type="file" multiple="multiple">
<input type="hidden" name="recaptcha_response" id="recaptchaResponse">
<input type="submit" id="submit-button" value="Send Files">
<div id="alertm"></div>
</form>
<script>
$('#contact-form').submit(function(event) {
event.preventDefault();
$('#alertm').text('Processing...').fadeIn(0);
grecaptcha.ready(function () {
grecaptcha.execute('xxxrecaptcha3-site_keyxxx', { action: 'contact' }).then(function (token) {
var recaptchaResponse = document.getElementById('recaptchaResponse');
recaptchaResponse.value = token;
// Make the Ajax call here
$.ajax({
url: 'testmailer.php',
type: 'post',
data: $('#contact-form').serialize(),
dataType: 'json',
success: function( _response ){
// The Ajax request is a success. _response is a JSON object
var error = _response.error;
var success = _response.success;
if(error != "") {
// In case of error, display it to user
$('#alertm').html(error);
}
else {
// In case of success, display it to user and remove the submit button
$('#alertm').html(success);
$('#submit-button').remove();
}
},
error: function(jqXhr, json, errorThrown){
// In case of Ajax error too, display the result
var error = jqXhr.responseText;
$('#alertm').html(error);
}
});
});
});
});
</script>
</body>
</html>
The mail sending script
<?php
require $_SERVER['DOCUMENT_ROOT'] . '/PHPMailer/src/PHPMailer.php';
use PHPMailer\PHPMailer\PHPMailer;
$mail = new PHPMailer();
if(isset($_POST['fname'])){
$name=$_POST['fname'];
}
function isValid() {
if($_POST['name'] != "") {
return true;
} else {
return false;
}
}
$email_to = "email#domain.com";
$mail->setFrom('no-reply#somedomain.com', 'SomeDomain Mailer');
$mail->Subject = 'File Attachment';
$body = "Name - $name\n";
$mail->Body = $body;
if (array_key_exists('userfile', $_FILES)) {
for ($ct = 0; $ct < count($_FILES['userfile']['tmp_name']); $ct++) {
$uploadfile = tempnam(sys_get_temp_dir(), sha1($_FILES['userfile']['name'][$ct]));
$filename = $_FILES['userfile']['name'][$ct];
if (move_uploaded_file($_FILES['userfile']['tmp_name'][$ct], $uploadfile)) {
if (!$mail->addAttachment($uploadfile, $filename)) {
$msg .= 'Failed to attach file ' . $filename;
}
} else {
$body .= 'Failed to move file to ' . $uploadfile;
}
}
$mail->IsHTML(true);
$error_output = '';
$success_output = '';
if(isValid()) {
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_secret = '***recaptcha3-secret_key***';
$recaptcha_response = $_POST['recaptcha_response'];
$recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response);
$recaptcha = json_decode($recaptcha);
if ($recaptcha->success == true && $recaptcha->score >= 0.5 && $recaptcha->action == 'contact') {
$mail->send();
$success_output = "Your message sent successfully";
} else {
$error_output = "Something went wrong. Please try again later";
}
} else {
$error_output = "Please fill all the required fields";
}
$output = array(
'error' => $error_output,
'success' => $success_output
);
// Output needs to be in JSON format
echo json_encode($output);
}
?>

Ajax Form Submit not stay on same page

I have designed a Sidebar Floating Form with PhP/Ajax.
Here is the Link: http://logohour.com/form.html
Everything is fine but when a visitor fill and submit the form it routes to anther page for the confirmation.
I am using almost the same coding for clickable form and its working fine but here on this sidebar floating form somewhere I am mistaking may be in Ajax or PHP.
Ajax you may find in Page Source, Here is my PHP:
<?php
// Define some constants
define( "RECIPIENT_NAME", "John Smith" );
define( "RECIPIENT_EMAIL", "example#gmail.com" );
define( "EMAIL_SUBJECT", "SiderBar Visitor Message" );
// Read the form values
$ssuccess = false;
$Name = isset( $_POST['Name'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_POST['Name'] ) : "";
$Email = isset( $_POST['Email'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['Email'] ) : "";
$Phone = isset( $_POST['Phone'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['Phone'] ) : "";
$Country = isset( $_POST['Country'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['Country'] ) : "";
$Select = isset( $_POST['Select'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['Select'] ) : "";
$Message = isset( $_POST['Message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['Message'] ) : "";
// If all values exist, send the email
if ( $Name && $Email && $Phone && $Country && $Select && $Message ) {
$msgToSend = "Name: $Name\n";
$msgToSend .= "Email: $Email\n";
$msgToSend .= "Phone: $Phone\n";
$msgToSend .= "Sender Country: $Country\n";
$msgToSend .= "Sender Select: $Select\n";
$msgToSend .= "Message: $Message";
$recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
$headers = "From: " . $Name . " <" . $Email . ">";
$ssuccess = mail( $recipient, EMAIL_SUBJECT, $msgToSend, $headers );
}
// Return an appropriate response to the browser
if ( isset($_GET["ajax"]) ) {
echo $ssuccess ? "ssuccess" : "error";
} else {
?>
<html>
<head>
<title>Thanks!</title>
</head>
<body>
<?php if ( $ssuccess ) echo "<p>Thanks for sending your message! We'll get back to you shortly.</p>" ?>
<?php if ( !$ssuccess ) echo "<p>There was a problem sending your message. Please try again.</p>" ?>
<p>Click your browser's Back button to return to the page.</p>
</body>
</html>
<?php
}
?>
Here is the AJAX Source Code
var messageDDelay = 2000; // How long to display status messages (in milliseconds)
// Init the form once the document is ready
$(init);
// Initialize the form
function init() {
// Hide the form initially.
// Make submitForm() the form's submit handler.
// Position the form so it sits in the centre of the browser window.
// When the "Send us an email" link is clicked:
// 1. Fade the content out
// 2. Display the form
// 3. Move focus to the first field
// 4. Prevent the link being followed
$('a[href="#contact_form"]').click(function() {
$('#content').fadeTo('slow', .2);
$('#contact_form').fadeIn('slow', function() {
$('#Name').focus();
})
return false; });
// When the "Cancel" button is clicked, close the form
$('#cancel').click(function() {
$('#contact_form').fadeOut();
$('#content').fadeTo('slow', 1);
});
// When the "Escape" key is pressed, close the form
$('#contact_form').keydown(function(event) {
if (event.which == 27) {
$('#contact_form').fadeOut();
$('#content').fadeTo('slow', 1);}});}
// Submit the form via Ajax
function submitFForm() {
var contact_form = $(this);
// Are all the fields filled in?
if (!$('#Name').val() || !$('#Email').val() || !$('#Phone').val() || !$('#Country').val() || !$('#Select').val() || !$('#Message').val()) {
// No; display a warning message and return to the form
$('#incompleteMMessage').fadeIn().delay(messageDDelay).fadeOut();
contact_form.fadeOut().delay(messageDDelay).fadeIn();
} else {
// Yes; submit the form to the PHP script via Ajax
$('#sendingMMessage').fadeIn();
contact_form.fadeOut();
$.ajax({
url: contact_form.attr('action') + "?ajax=true",
type: contact_form.attr('method'),
data: contact_form.serialize(),
ssuccess: submitFFinished }); }
// Prevent the default form submission occurring
return false; }
// Handle the Ajax response
function submitFFinished(response) {
response = $.trim(response);
$('#sendingMMessage').fadeOut();
if (response == "ssuccess") {
// Form submitted ssuccessfully:
// 1. Display the ssuccess message
// 2. Clear the form fields
// 3. Fade the content back in
$('#successMMessage').fadeIn().delay(messageDDelay).fadeOut();
$('#Name').val("");
$('#Email').val("");
$('#Phone').val("");
$('#Country').val("");
$('#Selct').val("");
$('#Message').val("");
$('#content').delay(messageDDelay + 500).fadeTo('slow', 1);
} else {
// Form submission failed: Display the failure message,
// then redisplay the form
$('#failureMMessage').fadeIn().delay(messageDDelay).fadeOut();
$('#contact_form').delay(messageDDelay + 500).fadeIn(); } }
use your function like this:
$("#contact_form").submit(submitFForm);
You are not calling the submitFForm() function. Try setting a click event to the submit button or setting the "submit" event to the form, e.g:
$("#contact_form").submit(function(e) {
submitFForm();
e.preventDefault(); // avoid to execute the actual submit of the form.
});
I'm not sure if I understand correctly, but I think you're saying that this code isn't functioning correctly:
$('a[href="#contact_form"]').click(function() {
$('#content').fadeTo('slow', .2);
$('#contact_form').fadeIn('slow', function() {
$('#Name').focus();
})
return false;
});
Is that right? If so, try replacing it with this:
$('#sendMMessage').click(function(event) {
event.preventDefault();
$('#content').fadeTo('slow', .2);
$('#contact_form').fadeIn('slow', function() {
$('#Name').focus();
});
alert('successfully stopped the other page loading');
return false;
});
Using both event.preventDefault() and return false is the correct way to stop the expected redirect. Your jQuery selector also needed to be corrected.
$('#sendMMessage').click(function(e){
e.preventDefault();
.... ajax ...etc
})
You have to annulate the default submit behaviour.

AngularJS PHP contact cannot read property name

Basically I have a contact form made with angularJS and PHP. and thats hosted on 000webhost. When I'm sending a mail the mail goes through but it also gives me an error. I think thats the reason it doesnt display MessageSuccess or MessageError messages.
TypeError: Cannot read property 'name' of undefined
at app.js:119
at angular.min.js:81
at angular.min.js:112
at m.$get.m.$eval (angular.min.js:126)
at m.$get.m.$digest (angular.min.js:123)
at m.$get.m.$apply (angular.min.js:127)
at l (angular.min.js:81)
at P (angular.min.js:85)
at XMLHttpRequest.H.onload (angular.min.js:86)
the HTML:
<div id="websiteApp" class="contactRow" style="display: none;">
<form ng-submit="submitForm()" ng-controller="FormController" novalidate class="contactForm" name="form" ng-hide="loaded">
<input class="input" type="text" name="name" placeholder="SINU NIMI" ng-model="formData.name" ng-class="{'error' : errorName}">
<input class="input2" type="email" name="email" placeholder="SINU E-MAIL" ng-model="formData.email" ng-class="{'error' : errorEmail}">
<textarea name="message" ng-class="{'error' : errorTextarea}" placeholder="KIRJUTA MEILE" ng-model="formData.message" rows="5"></textarea>
<input class="saada" type="submit" value="SAADA!" name="submit">
<div ng-class="{'submissionMessage' : submission}" ng-bind="submissionMessage"></div>
</form>
</div>
App.js
var app = angular.module('kaidoweb', ['ngRoute', 'ngAnimate']).
config(['$routeProvider','$locationProvider', function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.
when('/', {
templateUrl: 'pages/index.html',
activetab: 'index',
controller: HomeCtrl
}).
otherwise({ redirectTo: '/' });
}]).run(['$rootScope', '$http', '$browser', '$timeout', "$route", function ($scope, $http, $browser, $timeout, $route) {
$scope.$on("$routeChangeSuccess", function (scope, next, current) {
$scope.part = $route.current.activetab;
});
}]);
/*app.config(['$locationProvider', function($location) {
$location.hashPrefix('!');
}]);*/
//Contact form
app.controller('FormController',function($scope, $http) {
// creating a blank object to hold our form information.
//$scope will allow this to pass between controller and view
$scope.formData = {};
// submission message doesn't show when page loads
$scope.submission = false;
// Updated code thanks to Yotam
var param = function(data) {
var returnString = '';
for (d in data){
if (data.hasOwnProperty(d))
returnString += d + '=' + data[d] + '&';
}
// Remove last ampersand and return
return returnString.slice( 0, returnString.length - 1 );
};
$scope.submitForm = function() {
$http({
method : 'POST',
url : 'process.php',
data : param($scope.formData), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data) {
if (!data.success) {
// if not successful, bind errors to error variables
$scope.errorName = data.errors.name;
$scope.errorEmail = data.errors.email;
$scope.errorTextarea = data.errors.message;
$scope.submissionMessage = data.messageError;
$scope.submission = true; //shows the error message
} else {
// if successful, bind success message to message
$scope.submissionMessage = data.messageSuccess;
$scope.formData = {}; // form fields are emptied with this line
$scope.submission = true; //shows the success message
}
});
};
});
and the PHP
<?php
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
if (empty($_POST['name']))
$errors['name'] = 'Name is required.';
if (empty($_POST['email']))
$errors['email'] = 'Email is required.';
if (empty($_POST['message']))
$errors['message'] = 'Message is required.';
// return a response ===========================================================
// response if there are errors
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
$data['messageError'] = 'Vaata üle punased alad!';
} else {
// if there are no errors, return a message
$data['success'] = true;
$data['messageSuccess'] = 'Tänan, et kirjutasid. Võtan ühendust nii pea kui saan.';
// CHANGE THE TWO LINES BELOW
$email_to = "email.to#khk.ee";
$email_subject = "KaidoWeb kiri";
$name = $_POST['name']; // required
$email_from = $_POST['email']; // required
$message = $_POST['message']; // required
$email_message = "Form details below.nn";
$email_message .= "Name: ".$name."n";
$email_message .= "Email: ".$email_from."n";
$email_message .= "Message: ".$message."n";
$headers = 'From: '.$email_from."rn".
'Reply-To: '.$email_from."rn" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
}
// return all our data to an AJAX call
echo json_encode($data);
Also another thing is I also host this site on GoDaddy when trying to send a mail there it says: POST http://www.kaidoweb.com/process.php 403 (Forbidden).
I would be immensely grateful if someone could give me some sort of solution here and if you need to see something more just ask.
This is how your PHP is setting the errors object it is returning to your Angular App:
if (empty($_POST['name']))
$errors['name'] = 'Name is required.';
if (empty($_POST['email']))
$errors['email'] = 'Email is required.';
if (empty($_POST['message']))
$errors['message'] = 'Message is required.';
As you can see, in each case it is setting a different key inside of the errors array. In your Angular code you don't account for this, you just assume that all of the keys will be set:
$scope.errorName = data.errors.name;
$scope.errorEmail = data.errors.email;
$scope.errorTextarea = data.errors.message;
You can fix this either in your PHP or in your Angular App. In PHP, you could use an integer array rather than an associative array:
if (empty($_POST['name']))
$errors[] = 'Name is required.';
if (empty($_POST['email']))
$errors[] = 'Email is required.';
if (empty($_POST['message']))
$errors[] = 'Message is required.';
Then in Angular just set the scope variable and modify the view with how it's displayed:
$scope.errors = data.errors;
<ul><li data-ng-repeat="error in errors">{{ error }}</li></ul>
Alternatively, in Angular just check if the keys are set before attempting to access them:
if(data.errors.hasOwnProperty('name') {
$scope.errorName = data.errors.name;
}
Update
I'm talking about this section of your angular code, specifically the case in the success callback where data.success is falsey:
$scope.submitForm = function() {
$http({
method : 'POST',
// ...
})
.success(function(data) {
if (!data.success) {
// if not successful, bind errors to error variables
$scope.errors = data.errors;
$scope.submission = true; //shows the error message
} else {
// ...
}
});
};
Since you're probably binding to e.g. {{ errorName }} in your view template, wherever that is, that will also have to be updated with what I have above if you switch your $error array to return with numerical indices.

Post error report by pressing a button jQuery not working

Small problem here, I need to place a button on my 404 page to ask people to submit an error.
The problem is that nothing is actually happens, I mean no mail is received and no errors are displayed, so I am confused.
My report is very basic, it collects all data of what my user did before getting 404
$site = "mySite.com";
$email = "donotreply#mySite.com";
$http_host = $_SERVER['HTTP_HOST'];
$server_name = $_SERVER['SERVER_NAME'];
$remote_ip = $_SERVER['REMOTE_ADDR'];
$request_uri = $_SERVER['REQUEST_URI'];
$cookie = $_SERVER["HTTP_COOKIE"];
$http_ref = $_SERVER['HTTP_REFERER'];
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$error_date = date("D M j Y g:i:s a T");
$subject = "404 Alert";
$headers = "Content-Type: text/plain"."\n";
$headers .= "From: ".$site." <".$email.">"."\n";
$message = "404 Error Report for ".$site."\n";
$message .= "Date: ".$error_date."\n";
$message .= "Requested URL: http://".$http_host.$request_uri."\n";
$message .= "Cookie: ".$cookie."\n";
$message .= "Referrer: ".$http_ref."\n";
$message .= "User Agent: ".$user_agent."\n";
$message .= "IP Address: ".$remote_ip."\n";
$message .= "Whois: http://ws.arin.net/cgi-bin/whois.pl?queryinput=".$remote_ip;
this is my form, all fields are hidden that are placed in the same file along with php code above
<form name="form" method="POST" id="report-form">
<div class="form">
<input type="hidden" name="message" value="$message">
<div class="done">
<p><strong>Thank you!</strong></p>
</div>
<div class="error">
<p><strong>Error!</strong> Sorry, something went wrong, please try again.</p>
</div>
<input type="hidden" name="visitor" value="">
<input type="hidden" name="submitted" value="submitted">
<input type="submit" name="submit" value="Submit" class="formSubmit" />
</div>
</form>
<script type="text/javascript" src="js/report_validation.js"><\/script>
here is my jQuery validation script, which I am trying to use, which is in the separate file named report_validation.js in js folder
$(document).ready ( function() {
$('.formSubmit').click(function() {
// Store values in variables
var form = $(this).closest('form');
var message = form.find('input[name=message]');
var submitted = form.find('input[name=submitted]');
var visitor = form.find('input[name=visitor]');
// Organize data
var data = 'message=' + message.val() + '&submitted=' + submitted.val() + '&visitor=' + visitor.val();
var request = $.ajax({
type: "POST",
url: "includes/report_form_mail.php",
data: data,
cache: false,
success: function (html) {
if (html == "true") {
form.find('.done').fadeIn(500).delay(4000).fadeOut(500);
}
},
error: function(jqXHR, textStatus, error) {
alert("Form Error: " + error);
}
});
return false;
});
});
here is my mailing script, which is also placed in the separate file and named report_form_mail.php in my incudes folder
// Check if form was submitted
if ($_POST['submitted'] && $_POST['visitor'] == '') {
// If valid, store values in variables
$site = "mySite.com";
$email = "donotreply#mySite.com";
$mes = stripslashes($_POST['message']);
$subject = "404 Alert";
$headers = "Content-Type: text/plain"."\n";
$headers .= "From: ".$site." <".$email.">"."\n";
$message = "Message: $mes";
// Send email
$sent = mail($email, $subject, $message, $headers);
if($sent) {
echo json_encode(true);
} else {
echo "Error: Mail could not be send.";
exit();
}
} else {
echo "Error: There was a problem with submitting the form";
exit();
}
Please help me to figure it all out
I have actually found an error myself.
The jQuery was not loaded to the page correctly so I have corrected it and my form works perfectly fine.
Thanks to all

Confirmation message not showing after form submission - jQuery/Ajax

I'm working with the tutorial here: http://designwoop.com/2012/07/tutorial-coding-a-jquery-popup-modal-contact-form/ and the form sending the data correctly. However, after clicking submit, the form just shows the "sending" message rather than showing the confirmation message. This happens when I test locally and on my development environment. I don't see any error messages in my console.
This is my first time working with ajax and I am a newbie with jQuery/JavaScript. Not sure what the problem is here. It seems that it is not reading the data as true. I changed True to False to see what would happen and it still doesn't work. Can anyone help, please?
FYI I am implementing this on a site that already calls the 1.3.2 jQuery library and can not remove the reference, so I have to use noConflict. This doesn't work when I reference only the older library.
My goal is to create a modal that pops up when a user enters the website, but not if a cookie is set or if there is already a specific div on the page they enter through.
Here are the scripts:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="/wcsstore/CVWEB/images/home/js/jquery.fancybox.js?v=2.0.6"></script>
<script type="text/javascript">
var jQuery_1_7_2 = jQuery.noConflict(true);
function validateEmail(email) {
var reg = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return reg.test(email);
}
jQuery_1_7_2(document).ready(function(){
var emailFormExists = jQuery_1_7_2('#e2ma_signup_form');
if (document.cookie.indexOf('visited=true') == -1 && !(emailFormExists.length)){
var fifteenDays = 1000*60*60*24*15;
var expires = new Date((new Date()).valueOf() + fifteenDays);
document.cookie = "visited=true;expires=" + expires.toUTCString();
jQuery_1_7_2.fancybox({width:"100%", inline:true, href:"#inline"});
}
else
{
jQuery_1_7_2('#e2ma_signup_form').length
var fifteenDays = 1000*60*60*24*15;
var expires = new Date((new Date()).valueOf() + fifteenDays);
document.cookie = "visited=true;expires=" + expires.toUTCString();
}
jQuery_1_7_2("#contact").submit(function() { return false; });
jQuery_1_7_2("#send").on("click", function(){
var emailval = jQuery_1_7_2("#email").val();
var mailvalid = validateEmail(emailval);
if(mailvalid == false) {
jQuery_1_7_2("#email").addClass("error");
}
else if(mailvalid == true){
jQuery_1_7_2("#email").removeClass("error");
}
if(mailvalid == true) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
jQuery_1_7_2("#send").replaceWith("<em>sending...</em>");
jQuery_1_7_2.ajax({
type: 'POST',
url: 'http://lcoawebservices.com/scripts/email-opt-in.php',
data: jQuery_1_7_2("#contact").serialize(),
success: function(data) {
if(data == "true") {
jQuery_1_7_2("#contact").fadeOut("fast", function(){
jQuery_1_7_2(this).before("<p><strong>Thanks for opting in!</strong></p>");
setTimeout("jQuery_1_7_2.fancybox.close()", 1000);
});
}
}
});
}
});
});
</script>
and here is the HTML:
<div id="inline">
<h2>Join the our mailing list!</h2>
<form id="contact" name="contact" action="#" method="post">
<label for="email">Your E-mail</label>
<input type="email" id="email" name="email" class="txt">
<button id="send">Send E-mail</button>
</form>
</div>
here is the php (which i am also new to)
<?php
$sendto = "llantz#lecreuset.com";
$usermail = $_POST['email'];
$content = nl2br($_POST['msg']);
$subject = "New Feedback Message";
$headers = "From: " . strip_tags($usermail) . "\r\n";
$headers .= "Reply-To: ". strip_tags($usermail) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html;charset=utf-8 \r\n";
$msg = "<html><body style='font-family:Arial,sans-serif;'>";
$msg .= "<h2 style='font-weight:bold;border-bottom:1px dotted #ccc;'>New User Feedback</h2>\r\n";
$msg .= "<p><strong>Sent by:</strong> ".$usermail."</p>\r\n";
$msg .= "<p><strong>Message:</strong> ".$content."</p>\r\n";
$msg .= "</body></html>";
if(#mail($sendto, $subject, $msg, $headers)) {
echo "true";
} else {
echo "false";
}
?>
I figured it out - this is due to a cross-domain access problem. I do not have the answer on how to solve it yet but wanted to post this so no one else spends time looking at my code, trying to fix it.

Categories