我正在尝试使用recaptcha与PHP和AJAX,我被卡住了。出于某种原因,每当我尝试从$ _POST中取出一些东西时,我都会收到错误消息。
我正在运行PHP 4.4。
<?php
require_once('includes/recaptchalib.php');
define("PRIV_KEY", "yesthereisakeyhere");
$name = $_POST['name']; // This line comes back as undefined index
$email = $_POST['email']; //This line comes back as undefined index
if(in_array('', array($name, $email))) {
//one (or more) of the required fields is empty
$result = "field_error";
} else {
$resp = recaptcha_check_answer (PRIV_KEY, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); // 2 more undefined index errors here.
if (!$resp->is_valid) {
//Captcha was entered incorrectly
$result = "captcha_error";
} else {
//Captcha was entered correctly
$result = "success";
//mail function goes in here.
}
}
echo $result;
?>
这是我的HTML供参考:
<?php
require_once('includes/recaptchalib.php');
define("PUB_KEY", "yesthereisakeyhere");
?>
<form class="form" method="post">
<label>Name *</label>
<input type="text" name="name" class="required" />
<label>Email *</label>
<input type="text" name="email" class="required" />
<?php echo recaptcha_get_html(PUB_KEY); ?>
<input type="submit" value="GET A QUOTE" />
</form>
这是我的AJAX调用参考:
$("#locator-quote input[type=submit]").click(function() {
$(".message").removeClass("success").removeClass("error").addClass("loader").html("Sending message").fadeIn("slow");
$.ajax({
type: "POST",
url: "ajax.php",
data: $(this).serialize(),
dataType: 'text',
success: function(msg){
$('body').prepend('<h1>' + msg + '</h1>') /// This line is for testing
switch(msg) {
case "field_error": // one or more fields is/are empty
$(".message").removeClass("loader").addClass("error");
$(".message").html("Please fill in all the required fields.");
break;
case "captcha_error": // captcha wasn't typed correctly
$(".message").removeClass("loader").addClass("error");
$(".message").html("Please type the words correctly and try again!");
break;
case "success": // all good
$(".message").removeClass("loader").addClass("success");
$(".message").html("Your message has been sent. You'll soon hear from us!");
break;
default: // Hmm. The default case. You never know.
alert("Something is wrong. Please try again.");
}
}
});
Recaptcha.reload();
return false;
});
答案 0 :(得分:1)
问题是你试图序列化按钮而不是表格。
您正在收听$("#locator-quote input[type=submit]").click
事件,因此this
将成为按钮。
您需要序列化表单。
$(this).closest('form').serialize()
或者,而是绑定到表单的.submit
事件。
$('.form').submit(function(){
var data = $(this).serialize();
return false;
});