如何将Google Recaptcha集成到我现有的AJAX联系表单中

时间:2014-12-18 23:12:43

标签: php jquery ajax forms recaptcha

我是PHP和AJAX / Javascript编码的新手。我创建了一个通过Jquery验证的AJAX联系表单。我可以让客户端配置得很好,但我不知道如何将recaptcha的验证集成到我现有的标记中。

我的表单标记是这样的:

<!-- DIV used to display messages to Client -->
<div id="messages"></div>
<!-- Start of Contact Form -->
<div id="form">
<form id="contact" method="post" action="/scripts/php/mailer.php">

<div class="field">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
</div>

<div class="field">
<label for="email">Email:</label>
<input type="text" id="email" name="email" required>
</div>

<div class="field clear">
<label for="subject" id="type" name="type" required>Subject:</label>
<select>
<option value="none" selected="selected">-Please Select-</option>
<option value="Business Inquiry">Business Inquiry</option>
<option value="Product Feedback">Product Feedback</option>
<option value="Question or Comment">Question/Comment</option>
<option value="Website Error">Website Error</option>
<option value="Other">Other [Please Explain]</option>
</select>
</div>

<div class="field">
<label for="message">Message:</label>
<textarea id="message" name="message" required></textarea>
</div>

<div class="field">
<div class="g-recaptcha floatright" style="padding: 0 15px 15px 15px;" data-sitekey="mysitekey"></div>
</div>

<div class="field">
<button type="submit">Send</button>
</div>

</form>
</div>
<!-- END of Contact Form -->

我的Javascript文件是这样的:

$(function() {

var form = $('#contact');
var formMessages = $('#messages');
var content = $('#form');

// Set Up Event Listener for Contact Form
$(form).submit(function(event) {
    event.preventDefault();

    // Serialize the form data with JQuery
    var formData = $(form).serialize();

    // Submit the form using AJAX
    $.ajax({
    type: 'POST',
    url: $(form).attr('action'),
    data: formData
    })

    .done(function(response) {
    // Make sure that the formMessages div has the 'success' class.
    $(formMessages).removeClass('error');
    $(formMessages).addClass('success');
    $(formMessages).text(response);
    $(content) .html('<div></div>');

    // Clear the form.
    $('#name').val('');
    $('#email').val('');
    $('#message').val('');
    })

    .fail(function(data) {
    // Make sure that the formMessages div has the 'error' class.
    $(formMessages).removeClass('success');
    $(formMessages).addClass('error');

    // Set the message text.
    if (data.responseText !== '') {
    $(formMessages).text(data.responseText);
  } else {
    $(formMessages).text('There was an error and your message could not be sent at this time. Please try again later.');
  }
    });
  });
});

我目前的PHP是这样的:

<?php

// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get the form fields and remove whitespace.
    $name = strip_tags(trim($_POST["name"]));
            $name = str_replace(array("\r","\n"),array(" "," "),$name);
    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
    $type = trim($_POST["type"]);
    $message = trim($_POST["message"]);

    // Check that data was sent to the mailer.
    if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        // Set a 400 (bad request) response code and exit.
        http_response_code(400);
        echo "There was a problem with your submission. All fields are required! You must provide a valid email address. Please complete the form and try again.";
        exit;
    }

    // Set the recipient email address.
    $recipient = "my email";

    // Set the email subject.
    $subject = " Website Feedback from $name ";

    // Build the email content.
    $email_content = "Name: $name\n";
    $email_content .= "Email: $email\n\n";
    $email_content .= "Subject: $type\n\n";
    $email_content .= "Message:\n$message\n";

    // Build the email headers.
    $email_headers = "From: $name <$email>";

    // Send the email.
    if (mail($recipient, $subject, $email_content, $email_headers)) {
        // Set a 200 (okay) response code.
        http_response_code(200);
        echo "Thank You! Your message has been sent. Someone will get back to you as soon as possible (if applicable.)";
    } else {
        // Set a 500 (internal server error) response code.
        http_response_code(500);
        echo "Uh oh... Something went wrong and we couldn't send your message right now. Please try again in a moment!";
    }

} else {
    // Not a POST request, set a 403 (forbidden) response code.
    http_response_code(403);
    echo "There was a problem with your submission, please try again.";
}

?>

Google声明如下:

当您的用户提交集成了reCAPTCHA的表单时,您将获得一个名为&#34; g-recaptcha-response&#34;的字符串作为有效负载的一部分。要检查Google是否已验证该用户,请使用以下参数发送GET请求: 网址:https://www.google.com/recaptcha/api/siteverify 秘密(必填)我独特的sitekey 响应(必填)&#39; g-recaptcha-response&#39;的值。 remoteip最终用户的IP地址。 (可选)

我不知道如何修改我的php脚本,以便它在提交之前执行recaptcha和jquery验证。请帮忙!

0 个答案:

没有答案