scorpion
scorpion

Reputation: 11

Google Recaptcha (Contact Still Send Through)

I am having issue with my contact page and would be very much appreciated someone could help me with the google recaptcha coding.

I have added all the scripts and keys into my html. It is showing in my website but my contact page stills goes through even if I did not click on the recaptcha. I know it is my java script that is passing through the recaptcha. Below is the html code, javascript and php codings. Hope someone can let me know what went wrong.

HTML Code:

<div class="col-md-6 col-md-6">
                    <h3 class="title">Contact Form</h3>
                    <p class="form-message"></p>
                    <div class="contact-form">
                        <!-- Form Begins -->
                        <form role="form" name="contactform" id="contactform" method="post" action="php/contact-form-recaptcha.php">
                            <div class="row">
                                <div class="col-md-6">
                                    <!-- Field 1 -->
                                    <div class="input-text form-group">
                                        <input type="text" name="contact_name" class="input-name form-control"
                                        placeholder="Full Name" />
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <!-- Field 2 -->
                                    <div class="input-email form-group">
                                        <input type="email" name="contact_email" class="input-email form-control"
                                        placeholder="Email" />
                                    </div>
                                </div>
                            </div>
                            <!-- Field 3 -->
                            <div class="input-email form-group">
                                <input type="text" name="contact_phone" class="input-phone form-control" placeholder="Phone" />
                            </div>
                            <!-- Field 4 -->
                            <div class="textarea-message form-group">
                                <textarea name="contact_message" class="textarea-message form-control" placeholder="Message"
                                rows="6"></textarea>
                            </div></DIV>
                            <!-- Captcha Box -->
                            <div class="g-recaptcha" data-sitekey="6************************************Z"></div>
                            <!-- Button -->
                            <button class="btn btn-default" type="submit">Send Now 
                            <i class="icon-paper-plane"></i></button>
                        </form>
                        <!-- Form Ends -->
                    </div>

Javascript (This is the javascript that is passing through the recaptcha if all the fields are filled):

/* ---------------------    
    Contact Form  
/* --------------------- */
simplecontactForm: function(){  
    if ( $( "#contactform" ).length !== 0 ) {
    $('#contactform').bootstrapValidator({
            container: 'tooltip',
            feedbackIcons: {
                valid: 'fa fa-check',
                warning: 'fa fa-user',
                invalid: 'fa fa-times',
                validating: 'fa fa-refresh'
            },
            fields: { 
                contact_name: {
                    validators: {
                        notEmpty: {
                            message: ''
                        }
                    }
                },
                contact_email: {
                    validators: {
                        notEmpty: {
                            message: ''
                        },
                        emailAddress: {
                            message: ''
                        },
                        regexp: {
                                regexp: '^[^@\\s]+@([^@\\s]+\\.)+[^@\\s]+$',
                                message: 'The value is not a valid email address'
                        }
                    }
                },
                contact_phone: {
                    validators: {
                        notEmpty: {
                            message: ''
                        }
                    }
                },
                contact_message: {
                    validators: {
                        notEmpty: {
                            message: ''
                        }
                    }
                },
            }
        })  
        .on('success.form.bv', function(e) {
            e.preventDefault();
            var $form        = $(e.target),
            validator    = $form.data('bootstrapValidator'),
            submitButton = validator.getSubmitButton();
            var form_data = $('#contactform').serialize();
            $.ajax({
                    type: "POST",
                    dataType: 'json',
                    url: "../php/contact-form-recaptcha.php",                   
                    data: form_data,
                    success: function(msg){                     
                        $('.form-message').html(msg.data);
                        $('.form-message').show();
                        submitButton.removeAttr("disabled");
                        resetForm($('#contactform'));                       
                    },
                    error: function(msg){}
             });
            return false;
        });
    }
    function resetForm($form) {

        $form.find(
                'input:text, input:password, input, input:file, select, textarea'
            )
            .val('');

        $form.find('input:radio, input:checkbox')
            .removeAttr('checked')
            .removeAttr('selected');
        $form.find('button[type=submit]')
            .attr("disabled", "disabled");

    }
},

PHP (contact-form-recaptcha.php):

<?php
    if(isset($_POST['submit']) && !empty($_POST['submit'])):
    if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])):
    //your site secret key
    $secret = '6*****************************u';
    //get verify response data
    $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
    $responseData = json_decode($verifyResponse);
    if($responseData->success):
        //contact form submission code
        $to_email = "[email protected]"; // email address to which the form data will be sent
        $subject = "Contact Request"; // subject of the email that is sent
        $thanks_page = "index.html"; // path to the thank you page following successful form submission
        $contact_page = "index.html"; // path to the HTML contact page where the form appears

        $nam = strip_tags($_POST["contact_name"]);
        $ema = strip_tags($_POST["contact_email"]);
        $pho = strip_tags($_POST["contact_phone"]);
        $com = strip_tags($_POST["contact_message"]);

        // Always set content-type when sending HTML email
        $headers = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
        // More headers
        $headers .= 'From:'.$nam.' <'.$ema.'>' . "\r\n";
        //send email
        $email_body = 
        "<strong>From: </strong>" . $nam . "<br />
        <strong>Email: </strong>" . $ema . "<br />  
        <strong>Phone: </strong>" . $pho . "<br />  
        <strong>Message: </strong>" . $com;

        $succMsg = 'Your contact request have submitted successfully.';
    else:
        $errMsg = 'Robot verification failed, please try again.';
    endif;
else:
    $errMsg = 'Please click on the reCAPTCHA box.';
endif;
else:
$errMsg = '';
$succMsg = '';
endif;
?>

Please help me... Thanks a million...

Upvotes: 1

Views: 405

Answers (1)

Jainil
Jainil

Reputation: 1496

If you want to check if the User clicked on the I'm not a robot checkbox, you can use the .getResponse() function provided by the reCaptcha API.

It will return an empty string in case the User did not validate himself, something like this:

if(grecaptcha.getResponse() == "")
    alert("You can't proceed!");
else
    alert("Thank you");

In case the User has validated himself, the response will be a very long string.

More about the API can be found on this page: reCaptcha Javascript API

Upvotes: 1

Related Questions