Javascript 添加ReCaptcha后获取意外标识符
我收到一条错误消息:Javascript 添加ReCaptcha后获取意外标识符,javascript,php,ajax,Javascript,Php,Ajax,我收到一条错误消息: Uncaught SyntaxError: Unexpected identifier 在线33 这是在将Google ReCaptcha添加到我的AJAX联系人表单之后。我已经回顾了这一点,但我似乎无法找出我遗漏了什么 也许一双新的眼睛能发现我的错误 JS: $(window).load(function() { $("#loader").fadeOut("slow"); $('#main').fadeIn("slow"); }); $(document
Uncaught SyntaxError: Unexpected identifier
在线33
这是在将Google ReCaptcha添加到我的AJAX
联系人表单之后。我已经回顾了这一点,但我似乎无法找出我遗漏了什么
也许一双新的眼睛能发现我的错误
JS:
$(window).load(function() {
$("#loader").fadeOut("slow");
$('#main').fadeIn("slow");
});
$(document).ready(function(){
jQuery.validator.setDefaults({
errorPlacement : function(error, element) {
element.removeClass('has-success').addClass('has-error');
}
});
$('#emailForm').validate( {
submitHandler : function(form) {
return false;
},
rules : {
userEmail:{
required: true,
email: true
},
userName:{
required : true,
minlength : 3,
maxlength : 50
},
subject: {
required : true,
minlength : 10
},
message: {
required : true,
minlength : 50
}
recaptcha_response_field: {
required: true,
checkCaptcha: true
},
},
messages : {
userEmail:{
required : "Please enter your Email"
},
recaptcha_response_field: {
checkCaptcha: "Your Captcha response was incorrect. Please try again."
},
userName:{
required : "Please enter your name"
},
subject: {
required : "Please enter your contact purpose",
minlength : "Minimum length of subject must be 10 chars long."
},
message: {
required : "Please enter your sweet message",
minlength : "Minimum length of your message must be 50 chars long."
}
},
errorPlacement : function(error, element) {
$(element).closest('div.form-group').find('.help-block').html(error.html());
},
highlight : function(element) {
$(element).closest('div.form-group').removeClass('has-success').addClass('has-error');
},
unhighlight: function(element, errorClass, validClass) {
$(element).closest('div.form-group').removeClass('has-error').addClass('has-success');
$(element).closest('div.form-group').find('.help-block').html('');
}
});
$(document).on('click', '#sendMailBtn', function(e){
e.preventDefault();
if( $('#emailForm').valid() ) {
var sendMailBtn = $('#sendMailBtn');
sendMailBtn.button('loading');
$.ajax({
url: 'ajax.php',
method: 'post',
dataType: 'json',
data : { data:
JSON.stringify($('#emailForm').serializeObject())
recaptcha_challenge_field: Recaptcha.get_challenge()
recaptcha_response_field: Recaptcha.get_response()
},
captcha: grecaptcha.getResponse(),
success: function( response ){
(resp) ->
if resp is "true"
isCaptchaValid = true
else
Recaptcha.reload()
)
return isCaptchaValid
), ""
sendMailBtn.button('reset');
$('input,textarea').val('');
showSuccessMessage();
},
error: function( response ) {
sendMailBtn.button('reset');
if( response.status === 400 || response.status === 403 || response.status === 500 ) {
showWarningMessage(response.responseJSON.message);
} else {
showWarningMessage();
}
}
});
}
return false;
});
function showSuccessMessage(){
swal({
title: "Many Thanks!!!",
text: "Thanks for contacting us, We will get back to your inbox shortly...",
type: "success",
html: true
/*imageUrl: "img/thumbs-up.jpg"*/
});
}
function showWarningMessage(message){
if(typeof message === 'undefined' || message === '' ) message = "Something went wrong, Please try again.";
swal({
title: "Oops...",
text: message,
type: "error",
html: true
});
}
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
});
<?php
require_once 'config.php';
require 'vendor/autoload.php';
$response = [
'status' => 'success',
'message' => 'Mail sent successfully',
'data' => []
];
//Checking is it ajax request
if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') {
//Invalid Ajax request
http_response_code(403);
$response = [
'status' => 'error',
'message' => 'Invalid request, please try again.',
'data' => []
];
responseHandler($response);
}
if( !isset($_POST['data']) ) {
http_response_code(400);
$response = [
'status' => 'error',
'message' => 'Empty post data.',
'data' => []
];
responseHandler($response);
}
$data = json_decode($_POST['data'], true); $errors = '';
//Email validation
if ( isset($data["userEmail"]) && !empty( $data["userEmail"] ) ) {
$email = trim($data["userEmail"]);
if ( filter_var($email, FILTER_VALIDATE_EMAIL) === false){
$errors .= "$email is <strong>NOT</strong> a valid email address.<br/>";
}
} else {
$errors .= 'Please enter your email address.<br/>';
}
//Name Validation
if ( isset($data["userName"]) && !empty( $data["userName"] ) ) {
$name = trim( $data["userName"] );
if ( filter_var($name, FILTER_SANITIZE_STRING) === false){
$errors .= 'Please enter a valid name.<br/>';
} elseif (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$errors .= 'Only letters and white space allowed for name...<br/>';
}
} else {
$errors .= 'Please enter your name.<br/>';
}
//Subject Validation
if ( isset($data["subject"]) && !empty( $data["subject"] ) ) {
$subject = trim( $data["subject"] );
if ( filter_var($subject, FILTER_SANITIZE_STRING) === false){
$errors .= 'Please enter a subject to send.<br/>';
}
} else {
$errors .= 'Please enter a subject to send.<br/>';
}
//Message Validation
if ( isset($data["message"]) && !empty( $data["message"] ) ) {
$message = trim( $data["message"] );
if ( filter_var($message, FILTER_SANITIZE_STRING) === false){
$errors .= 'Please enter a message to send.<br/>';
}
} else {
$errors .= 'Please enter a message to send.<br/>';
}
//Google ReCaptcha
if ( isset($_POST["captcha"]) ) {
require('component/recaptcha/src/autoload.php');
$recaptcha = new \ReCaptcha\ReCaptcha(SECRET_KEY, new \ReCaptcha\RequestMethod\SocketPost());
$resp = $recaptcha->verify($_POST['captcha'], $_SERVER['REMOTE_ADDR']);
if (!$resp->isSuccess()) {
$errors .= 'Captcha is required.<br/>';
}
}
if(!empty( $errors )) {
http_response_code(400);
$response = [
'status' => 'error',
'message' => $errors,
'data' => []
];
responseHandler($response);
}
//Filtering out newlines in the email subject
$subject = str_replace(array("\r","\n"),array(" "," "),$subject);
$contactContent = file_get_contents('email_templates/contact.html');;
$parameters = ['name' => $name, 'to_name' => TO_NAME, 'message' => $message ];
if(! send_mail( $email, $subject, $contactContent, $parameters ) ){
//Email sent failed.
http_response_code(500);
$response = [
'status' => 'error',
'message' => 'Email service failing temporarily Or Maybe you are entered invalid E-mail, Please enter valid email and try again.',
'data' => []
];
responseHandler($response);
} else {
//Email successfully sent
http_response_code(200);
responseHandler($response);
}
/**
* responseHandler function
* @param array $response request response
*/
function responseHandler($response)
{
header('Content-type: application/json');
echo json_encode($response);
exit;
}
/**
* send_mail function
* @param string $email [[Description]]
* @param string $Subject [[Description]]
* @param string $message [[Description]]
* @param array [$parameters = []] [[Description]]
* @return boolean [[Description]]
*/
function send_mail($email, $Subject, $message, $parameters = []){
////Parse the message with given parameters
if( !empty( $parameters ) )$message = parse($message, $parameters);
$mail = new PHPMailer;
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = SMTP_HOST; // Specify main and backup SMTP servers
$mail->SMTPAuth = SMTP_AUTH; // Enable SMTP authentication
$mail->Username = SMTP_USERNAME;
$mail->Password = SMTP_PASSWORD;
$mail->SMTPSecure = SMTP_SECURE; // Enable TLS encryption, `ssl` also accepted
$mail->Port = SMTP_PORT; // TCP port to connect to
if( isset($parameters['name']) )
$mail->setFrom($email, $parameters['name']);
else
$mail->setFrom($email);
$mail->addAddress(TO_EMAIL); // Add a recipient
//$mail->addReplyTo($email, 'Smart Invoice V3 Promotion');
$mail->addBCC(TO_EMAIL);
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $Subject;
$mail->Body = $message;
$mail->AltBody = strip_tags($message);
if(!$mail->send()) {//$mail->ErrorInfo;
return false;
}
return true;
}
/**
* parse function
* @param string $message [[Description]]
* @param array $parameters [[Description]]
* @return string [[Description]]
*/
function parse($message, $parameters) {
foreach ($parameters as $key => $value) {
$message = str_replace('{'.$key.'}', $value, $message);
}
return $message;
}
PHP:
$(window).load(function() {
$("#loader").fadeOut("slow");
$('#main').fadeIn("slow");
});
$(document).ready(function(){
jQuery.validator.setDefaults({
errorPlacement : function(error, element) {
element.removeClass('has-success').addClass('has-error');
}
});
$('#emailForm').validate( {
submitHandler : function(form) {
return false;
},
rules : {
userEmail:{
required: true,
email: true
},
userName:{
required : true,
minlength : 3,
maxlength : 50
},
subject: {
required : true,
minlength : 10
},
message: {
required : true,
minlength : 50
}
recaptcha_response_field: {
required: true,
checkCaptcha: true
},
},
messages : {
userEmail:{
required : "Please enter your Email"
},
recaptcha_response_field: {
checkCaptcha: "Your Captcha response was incorrect. Please try again."
},
userName:{
required : "Please enter your name"
},
subject: {
required : "Please enter your contact purpose",
minlength : "Minimum length of subject must be 10 chars long."
},
message: {
required : "Please enter your sweet message",
minlength : "Minimum length of your message must be 50 chars long."
}
},
errorPlacement : function(error, element) {
$(element).closest('div.form-group').find('.help-block').html(error.html());
},
highlight : function(element) {
$(element).closest('div.form-group').removeClass('has-success').addClass('has-error');
},
unhighlight: function(element, errorClass, validClass) {
$(element).closest('div.form-group').removeClass('has-error').addClass('has-success');
$(element).closest('div.form-group').find('.help-block').html('');
}
});
$(document).on('click', '#sendMailBtn', function(e){
e.preventDefault();
if( $('#emailForm').valid() ) {
var sendMailBtn = $('#sendMailBtn');
sendMailBtn.button('loading');
$.ajax({
url: 'ajax.php',
method: 'post',
dataType: 'json',
data : { data:
JSON.stringify($('#emailForm').serializeObject())
recaptcha_challenge_field: Recaptcha.get_challenge()
recaptcha_response_field: Recaptcha.get_response()
},
captcha: grecaptcha.getResponse(),
success: function( response ){
(resp) ->
if resp is "true"
isCaptchaValid = true
else
Recaptcha.reload()
)
return isCaptchaValid
), ""
sendMailBtn.button('reset');
$('input,textarea').val('');
showSuccessMessage();
},
error: function( response ) {
sendMailBtn.button('reset');
if( response.status === 400 || response.status === 403 || response.status === 500 ) {
showWarningMessage(response.responseJSON.message);
} else {
showWarningMessage();
}
}
});
}
return false;
});
function showSuccessMessage(){
swal({
title: "Many Thanks!!!",
text: "Thanks for contacting us, We will get back to your inbox shortly...",
type: "success",
html: true
/*imageUrl: "img/thumbs-up.jpg"*/
});
}
function showWarningMessage(message){
if(typeof message === 'undefined' || message === '' ) message = "Something went wrong, Please try again.";
swal({
title: "Oops...",
text: message,
type: "error",
html: true
});
}
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
});
<?php
require_once 'config.php';
require 'vendor/autoload.php';
$response = [
'status' => 'success',
'message' => 'Mail sent successfully',
'data' => []
];
//Checking is it ajax request
if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') {
//Invalid Ajax request
http_response_code(403);
$response = [
'status' => 'error',
'message' => 'Invalid request, please try again.',
'data' => []
];
responseHandler($response);
}
if( !isset($_POST['data']) ) {
http_response_code(400);
$response = [
'status' => 'error',
'message' => 'Empty post data.',
'data' => []
];
responseHandler($response);
}
$data = json_decode($_POST['data'], true); $errors = '';
//Email validation
if ( isset($data["userEmail"]) && !empty( $data["userEmail"] ) ) {
$email = trim($data["userEmail"]);
if ( filter_var($email, FILTER_VALIDATE_EMAIL) === false){
$errors .= "$email is <strong>NOT</strong> a valid email address.<br/>";
}
} else {
$errors .= 'Please enter your email address.<br/>';
}
//Name Validation
if ( isset($data["userName"]) && !empty( $data["userName"] ) ) {
$name = trim( $data["userName"] );
if ( filter_var($name, FILTER_SANITIZE_STRING) === false){
$errors .= 'Please enter a valid name.<br/>';
} elseif (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$errors .= 'Only letters and white space allowed for name...<br/>';
}
} else {
$errors .= 'Please enter your name.<br/>';
}
//Subject Validation
if ( isset($data["subject"]) && !empty( $data["subject"] ) ) {
$subject = trim( $data["subject"] );
if ( filter_var($subject, FILTER_SANITIZE_STRING) === false){
$errors .= 'Please enter a subject to send.<br/>';
}
} else {
$errors .= 'Please enter a subject to send.<br/>';
}
//Message Validation
if ( isset($data["message"]) && !empty( $data["message"] ) ) {
$message = trim( $data["message"] );
if ( filter_var($message, FILTER_SANITIZE_STRING) === false){
$errors .= 'Please enter a message to send.<br/>';
}
} else {
$errors .= 'Please enter a message to send.<br/>';
}
//Google ReCaptcha
if ( isset($_POST["captcha"]) ) {
require('component/recaptcha/src/autoload.php');
$recaptcha = new \ReCaptcha\ReCaptcha(SECRET_KEY, new \ReCaptcha\RequestMethod\SocketPost());
$resp = $recaptcha->verify($_POST['captcha'], $_SERVER['REMOTE_ADDR']);
if (!$resp->isSuccess()) {
$errors .= 'Captcha is required.<br/>';
}
}
if(!empty( $errors )) {
http_response_code(400);
$response = [
'status' => 'error',
'message' => $errors,
'data' => []
];
responseHandler($response);
}
//Filtering out newlines in the email subject
$subject = str_replace(array("\r","\n"),array(" "," "),$subject);
$contactContent = file_get_contents('email_templates/contact.html');;
$parameters = ['name' => $name, 'to_name' => TO_NAME, 'message' => $message ];
if(! send_mail( $email, $subject, $contactContent, $parameters ) ){
//Email sent failed.
http_response_code(500);
$response = [
'status' => 'error',
'message' => 'Email service failing temporarily Or Maybe you are entered invalid E-mail, Please enter valid email and try again.',
'data' => []
];
responseHandler($response);
} else {
//Email successfully sent
http_response_code(200);
responseHandler($response);
}
/**
* responseHandler function
* @param array $response request response
*/
function responseHandler($response)
{
header('Content-type: application/json');
echo json_encode($response);
exit;
}
/**
* send_mail function
* @param string $email [[Description]]
* @param string $Subject [[Description]]
* @param string $message [[Description]]
* @param array [$parameters = []] [[Description]]
* @return boolean [[Description]]
*/
function send_mail($email, $Subject, $message, $parameters = []){
////Parse the message with given parameters
if( !empty( $parameters ) )$message = parse($message, $parameters);
$mail = new PHPMailer;
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = SMTP_HOST; // Specify main and backup SMTP servers
$mail->SMTPAuth = SMTP_AUTH; // Enable SMTP authentication
$mail->Username = SMTP_USERNAME;
$mail->Password = SMTP_PASSWORD;
$mail->SMTPSecure = SMTP_SECURE; // Enable TLS encryption, `ssl` also accepted
$mail->Port = SMTP_PORT; // TCP port to connect to
if( isset($parameters['name']) )
$mail->setFrom($email, $parameters['name']);
else
$mail->setFrom($email);
$mail->addAddress(TO_EMAIL); // Add a recipient
//$mail->addReplyTo($email, 'Smart Invoice V3 Promotion');
$mail->addBCC(TO_EMAIL);
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $Subject;
$mail->Body = $message;
$mail->AltBody = strip_tags($message);
if(!$mail->send()) {//$mail->ErrorInfo;
return false;
}
return true;
}
/**
* parse function
* @param string $message [[Description]]
* @param array $parameters [[Description]]
* @return string [[Description]]
*/
function parse($message, $parameters) {
foreach ($parameters as $key => $value) {
$message = str_replace('{'.$key.'}', $value, $message);
}
return $message;
}
“错误”,
'消息'=>'请求无效,请重试。',
“数据”=>[]
];
负责人($response);
}
如果(!isset($\u POST['data'])){
http_响应_代码(400);
$response=[
'状态'=>'错误',
'消息'=>'为空的post数据。',
“数据”=>[]
];
负责人($response);
}
$data=json_decode($_POST['data'],true)$错误='';
//电子邮件验证
if(设置($data[“userEmail”])和&!empty($data[“userEmail”])){
$email=trim($data[“userEmail”]);
if(filter\u var($email,filter\u VALIDATE\u email)==false){
$errors.=“$email不是有效的电子邮件地址。
”;
}
}否则{
$errors.=“请输入您的电子邮件地址。
”;
}
//名称验证
if(设置($data[“userName”])和&!empty($data[“userName”])){
$name=trim($data[“userName”]);
if(filter\u var($name,filter\u SANITIZE\u STRING)==false){
$errors.='请输入有效名称。
';
}elseif(!preg_match(“/^[a-zA-Z]*$/”,$name)){
$errors.='名称仅允许字母和空格…
';
}
}否则{
$errors.=“请输入您的姓名。
”;
}
//主题验证
if(设置($data[“subject”])和&!empty($data[“subject”])){
$subject=trim($data[“subject”]);
if(filter\u var($subject,filter\u SANITIZE\u STRING)==false){
$errors.=“请输入要发送的主题。
”;
}
}否则{
$errors.=“请输入要发送的主题。
”;
}
//消息验证
if(设置($data[“message”])和&!empty($data[“message”])){
$message=trim($data[“message”]);
if(filter\u var($message,filter\u SANITIZE\u STRING)==false){
$errors.=“请输入要发送的消息。
”;
}
}否则{
$errors.=“请输入要发送的消息。
”;
}
//谷歌雷帕查
如果(isset($_POST[“验证码])){
require('component/recaptcha/src/autoload.php');
$recaptcha=new\recaptcha\recaptcha(密钥,new\recaptcha\RequestMethod\SocketPost());
$resp=$recaptcha->verify($\u POST['captcha'],$\u服务器['REMOTE\u ADDR']);
如果(!$resp->issucess()){
$errors.=“需要验证码。
”;
}
}
如果(!empty($errors)){
http_响应_代码(400);
$response=[
'状态'=>'错误',
'message'=>$errors,
“数据”=>[]
];
负责人($response);
}
//过滤掉电子邮件主题中的换行符
$subject=str_replace(数组(“\r”、“\n”)、数组(“、”)、$subject);
$contactContent=file_get_contents('email_templates/contact.html');;
$parameters=['name'=>$name',to_name'=>to_name',message'=>$message];
如果(!发送邮件($email、$subject、$contactContent、$parameters)){
//发送电子邮件失败。
http_响应_代码(500);
$response=[
'状态'=>'错误',
“邮件”=>“电子邮件服务暂时失败,或者您输入的电子邮件无效,请输入有效的电子邮件并重试。”,
“数据”=>[]
];
负责人($response);
}否则{
//电子邮件已成功发送
http_响应_码(200);
负责人($response);
}
/**
*响应handler函数
*@param array$response请求响应
*/
函数responseHandler($response)
{
标题('Content-type:application/json');
echo json_编码($response);
出口
}
/**
*发送邮件功能
*@param string$email[[Description]]
*@param string$Subject[[Description]]
*@param string$message[[Description]]
*@param数组[$parameters=[][[Description]]
*@return boolean[[Description]]
*/
函数send_mail($email、$Subject、$message、$parameters=[])){
////使用给定参数解析消息
如果(!empty($parameters))$message=parse($message,$parameters);
$mail=新的PHPMailer;
//$mail->SMTPDebug=3;//启用详细调试输出
$mail->isSMTP();//设置邮件程序以使用SMTP
$mail->Host=SMTP\u Host;//指定主SMTP服务器和备份SMTP服务器
$mail->SMTPAuth=SMTP\u AUTH;//启用SMTP身份验证
$mail->Username=SMTP\u用户名;
$mail->Password=SMTP\u密码;
$mail->SMTPSecure=SMTP_SECURE;//启用TLS加密,也接受'ssl'
$mail->Port=SMTP\u Port;//要连接的TCP端口
if(isset($parameters['name']))
$mail->setFrom($email,$parameters['name']);
其他的
$mail->setFrom($email);
$mail->addAddress(发送电子邮件);//添加收件人
//$mail->addReplyTo($email,'Smart Invoice V3 Promotion');
$mail->addBCC(发送电子邮件);
$mail->isHTML(true);//将电子邮件格式设置为HTML
$mail->Subject=$Subject;
$mail->Body=$message;
$mail->AltBody=strip_标签($message);
如果(!$mail->send()){/$mail->ErrorInfo;
返回false;
}
返回true;
}
/**
*解析函数
*@param string$message[[Description]]
*@param数组$parameters[[Description]]
*@returnstring[[Description]]
*/
函数解析($message,$parameters){
foreach($key=>$value形式的参数){
$message=str_replace('{'.$key.'}',$value,$message);
}
返回$message;
}
我已将附加代码添加到Javascript中,以调用PHP脚本。验证应在客户端和服务器端执行
如果验证码有错误,则会将错误打印到$errors字符串,然后