通过ajax发布带有google recaptcha的表单

时间:2017-03-30 15:51:39

标签: javascript php jquery ajax forms

我有以下情况'与我联系'在OctoberCMS中形成(部分)

    <form name="sentMessage" id="contactForm" novalidate>
        <div class="row control-group">
            <div class="form-group col-xs-12 floating-label-form-group controls">
                <label>Name</label>
                <input type="text" class="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name.">
                <p class="help-block text-danger"></p>
            </div>
        </div>
        <div class="row control-group">
            <div class="form-group col-xs-12 floating-label-form-group controls">
                <label>Email Address</label>
                <input type="email" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address.">
                <p class="help-block text-danger"></p>
            </div>
        </div>
        <div class="row control-group">
            <div class="form-group col-xs-12 floating-label-form-group controls">
                <label>Phone Number</label>
                <input type="tel" class="form-control" placeholder="Phone Number" id="phone" required data-validation-required-message="Please enter your phone number.">
                <p class="help-block text-danger"></p>
            </div>
        </div>
        <div class="row control-group">
            <div class="form-group col-xs-12 floating-label-form-group controls">
                <label>Message</label>
                <textarea rows="5" class="form-control" placeholder="Message" id="message" required data-validation-required-message="Please enter a message."></textarea>
                <p class="help-block text-danger"></p>
            </div>
        </div>
        <br>
        <div class="g-recaptcha" id="gcaptcha" data-sitekey="sitekeydataCjaelksjEJlakch"></div>
        <div id="success"></div>
        <div class="row">
            <div class="form-group col-xs-12">
                <button type="submit" class="btn btn-success btn-lg">Send</button>
            </div>
        </div>
    </form>

当用户点击提交时 - 它通过javascript处理(这有助于输入验证)。我正在使用JQuery。

JS看起来像这样:

$(function() {
    $("input,textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
            // additional error messages or events
        },
        submitSuccess: function($form, event) {
            event.preventDefault(); // prevent default submit behaviour
            // get values from FORM
            var name = $("input#name").val();
            var email = $("input#email").val();
            var phone = $("input#phone").val();
            var message = $("textarea#message").val();
            var gcaptcha = $("#gcaptcha").data('sitekey');

            var firstName = name; // For Success/Failure Message
            // Check for white space in name for Success/Fail message
            if (firstName.indexOf(' ') >= 0) {
                firstName = name.split(' ').slice(0, -1).join(' ');
            }
            $.ajax({
                url: "././mail/contact_me.php",
                type: "POST",
                data: {
                    name: name,
                    phone: phone,
                    email: email,
                    message: message,
                    gcaptcha: gcaptcha
                },
                cache: false,
                success: function() {
                    // Success message
                    $('#success').html("<div class='alert alert-success'>");
                    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                        .append("</button>");
                    $('#success > .alert-success')
                        .append("<strong>Your message has been sent. </strong>");
                    $('#success > .alert-success')
                        .append('</div>');

                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
                error: function() {
                    // Fail message
                    $('#success').html("<div class='alert alert-danger'>");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                        .append("</button>");
                    $('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
                    $('#success > .alert-danger').append('</div>');
                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
            })
        },
        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});

contact_me.php表单如下所示:

<?php

// Check for empty fields
if(empty($_POST['name'])        ||
   empty($_POST['email'])       ||
   empty($_POST['phone'])       ||
   empty($_POST['message']) ||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
    echo "No arguments Provided!";
    return false;
   }

$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));
$secret = "alkfejasupersecretkeyalkjeociyseh13987fa9s8df7";
$gcaptcha = $_POST['gcaptcha'];
$remoteip = $_SERVER['REMOTE_ADDR'];

$url = "https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$gcaptcha."&remoteip=".$remoteip;
$result = json_decode($url, true);
var_dump($result);
/*
if ($result['success'] == 1) {
    //do mail here
}


// Create the email and send the message
$to = 'myemail@gmail.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form:  $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
*/
?>

正如你所看到的 - 我试图看看我是否能够接触到它不会出现的contact_me.php表格。在我发表评论之前 - 邮件从未发送过 - 这就是为什么我开始试图查看我的数据是否甚至点击了contact_me.php页面。我在提交时看到了成功消息 - 但数据永远不会消失,也没有电子邮件。

我可以在Firebug中看到数据发布到contact_me - 但我不能说明这一点。 var_dump不起作用,我需要进一步的帮助才能更好地解决这个问题或弄清楚什么是无效的。

1 个答案:

答案 0 :(得分:0)

在评论中得到Xorifelse的大量帮助后,我意识到代码可能很好(或者至少合适的)。

我最终走向了另一个方向。我稍微更新了表单,所以它看起来像这样:

<div class="container">
    <div class="row">
        <div class="col-lg-12 text-center">
            <h2>Contact Me</h2>
            <hr class="star-primary">
        </div>
    </div>
    <div class="row">
        <div class="col-lg-8 col-lg-offset-2">
            <form name="sentMessage" id="contactForm" data-request="onSend" data-request-success="alert('We have received your email. Thank you!'); this.reset();" novalidate>
                <div class="row control-group">
                    <div class="form-group col-xs-12 floating-label-form-group controls">
                        <label>Name</label>
                        <input name="name" type="text" class="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name.">
                        <p class="help-block text-danger"></p>
                    </div>
                </div>
                <div class="row control-group">
                    <div class="form-group col-xs-12 floating-label-form-group controls">
                        <label>Email Address</label>
                        <input name="email" type="email" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address.">
                        <p class="help-block text-danger"></p>
                    </div>
                </div>
                <div class="row control-group">
                    <div class="form-group col-xs-12 floating-label-form-group controls">
                        <label>Phone Number</label>
                        <input name="phone" type="tel" class="form-control" placeholder="Phone Number" id="phone" required data-validation-required-message="Please enter your phone number.">
                        <p class="help-block text-danger"></p>
                    </div>
                </div>
                <div class="row control-group">
                    <div class="form-group col-xs-12 floating-label-form-group controls">
                        <label>Message</label>
                        <textarea name="contact-msg" rows="5" class="form-control" placeholder="Message" id="contact-msg" required data-validation-required-message="Please enter a message."></textarea>                         
                        <p class="help-block text-danger"></p>
                    </div>
                </div>
                <br>
                <div class="g-recaptcha" id="sitekey" data-sitekey="gcaptchasitekey3897vadf834fadf"></div>
                <div id="success"></div>
                <div class="row">
                    <div class="form-group col-xs-12">
                        <button type="submit" class="btn btn-success btn-lg">Send</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

注意&#39; onSend&#39;数据请求参数。

在默认布局中 - 我把这个PHP片段用于处理实际处理(onSend函数):

function onSend()
{
  if(empty(post('name'))        ||
     empty(post('email'))       ||
     empty(post('phone'))       ||
     empty(post('contact-msg')) ||
     empty(post('g-recaptcha-response')) ||
     !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
     {
    echo "Please fill out all required fields.";
    return false;
     }
    // Collect input
    $name = post('name');
    $email = post('email');
    $phone = post('phone');
    $body = post('contact-msg');
    $response = post('g-recaptcha-response');
    $remoteip = $_SERVER['REMOTE_ADDR'];
    $secret = "32supersecretkeyackjaBcjeLCJelahd832CDo";
    $url = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$response."&remoteip=".$remoteip);
    $response = json_decode($url, true);

    // Form Validation
    $validator = Validator::make(
        [
            'name' => $name,
            'email' => $email,
            'phone' => $phone,
            'contact-msg' => $body,
        ],
        [
            'name' => 'required',
            'email' => 'required|email',
            'contact-msg' => 'required',
        ]
    );
    if ($validator->fails())
    {
        $messages = $validator->messages();
        throw new ApplicationException($messages->first());
    }

    // Make sure the captcha is verified before sending
    if (isset($response['success'])&&$response['success']=="true"){
      $to = config('mail.from.address');
      $params = compact('name','email','phone','body');
      Mail::sendTo($to, 'freelance::mail.contact', $params);

      return true;
    }
    else {

      return false;
    }

}

我能够将JS文件减少到:

$(function() {

    $("input,textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
            // additional error messages or events
        },

        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});


/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
    $('#success').html('');
});

因此,当用户输入时,它提供了主动验证(这很棒)。

此方法还需要在后端 一点额外设置:

您需要创建一个新的邮件模板&#39; (代码:freelance :: mail.contact)在后端的设置部分(当然,请确保您的邮件设置已设置)

一旦提交成功,我本来希望再做一点JS - 所以也许将来我会把它用到它 - 但现在这已经按照预期工作了。