Rex
Rex

Reputation: 233

Contact Form anti-spam JavaScript and/or PHP

I have a contact form I am using in a Bootstrap responsive single-page site. The form works just fine and sends the emails just fine. My site does not get a whole lot of traffic and I dislike the Captcha fields, so I wanted to insert a simple field for users to enter to ensure they are human. I added a simple math question. Now, I need to know how to validate that the user entered the correct math answer before the email is processed.

My form uses a contact_me.js file in combination with the jqBootstrapBalidation.js file to validate and send the form to the contact_me.php to process the email. I tried updating the PHP (with some suggestions from here) but I could not get it to work. It will always send the email through even if the math answer was entered incorrectly.

It is important to note that I did not write the code for this, I am very new to js. The form and code was supplied by startbootstrap.com templates.

I want to force the user to input the correct answer to the math question. I added this field myself. I added the variable for the human field to the contact_me.js file (I assume I needed to do this) to get the value from the form.

Further down on the .js file it then uses ajax to post to the contact_me.php to process the email. Below this is where it looks like it further validates the fields and displays the success/error messages. Is there someplace here I can verify if the user entered the correct math equation (answer should be =5) and if it is correct, then to process the email via the contact_me.php and if the answer is incorrect then to display an error message without sending to the php and ask to try again? Below is the html, contact_me.js and the contact_me.php. Thank you so much for your help with this!

HTML:

 <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>
                    <div class="row control-group">
                        <div class="form-group col-xs-12 floating-label-form-group controls">
                            <label>Human</label>
                            <input type="text" class="form-control" placeholder="Two + 3 = ?" id="human" required data-validation-required-message="Please solve math equation to prove you are human">
                            <p class="help-block text-danger"></p>
                        </div>
                    </div>
                     <br>
                    <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>

contact_me.js:

$(function() {

$("input,textarea").jqBootstrapValidation({
    preventSubmit: true,
    submitError: function($form, event, errors) {
        // additional error messages or events
    },
    submitSuccess: function($form, event) {
        // Prevent spam click and default submit behaviour
        $("#btnSubmit").attr("disabled", true);
        event.preventDefault();

        // 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 human = $("textarea#human").val();
        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,
                human: human
            },
            cache: false,
            success: function() {
                // Enable button & show success message
                $("#btnSubmit").attr("disabled", false);
                $('#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");
});
});

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

contact_me.php:

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

//Check if simple anti-bot test is correct
if ($human !== 5) {
   $errHuman = 'Your anti-spam is incorrect';
}   

$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$message = $_POST['human'];

// Create the email and send the message
$to = '[email protected]'; // Add your email address inbetween the '' replacing [email protected] - This is where the form will send a message to.
$email_subject = "Portfolio Website Message:  $name";
$email_body = "You have received a new message from your portfolio 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: [email protected]\n"; // This is the email address the generated message will be from. We recommend using something like [email protected].
$headers .= "Reply-To: $email_address"; 
mail($to,$email_subject,$email_body,$headers);
return true;            
?>

Upvotes: 0

Views: 2495

Answers (1)

SidTheBeard
SidTheBeard

Reputation: 379

It may be due to the code following your if statement in contact_me.php. It should read

if($human !== 5) {
    $errMsg = "Anti-Spam is incorrect";
} else {
    // CUT ALL CODE FOLLOWING YOUR IF AND PASTE IN BETWEEN THIS ELSE.
}

This will allow you to send the email if and only if the answer submitted is 5.

EDIT - JAVASCRIPT VALIDATION

You would have your Ajax function within this if else statement.

if(human === 5) {
/*
    PASTE AJAX FUNCTION
    CODE HERE, IT WILL RUN IF
    THEIR ANSWER IS CORRECT
*/
} else {
/*
    SEND ERROR FROM HERE
    IF THEIR ANSWER IS
    ANYTHING ELSE 
*/
}

Insert this code in the line where your Ajax code currently starts

2ND EDIT -

if(human === 5) {
    $.ajax({
        url: "././mail/contact_me.php",
        type: "POST",
        data: {
            name: name,
            phone: phone,
            email: email,
            message: message,
            human: human
        },
        cache: false,
        success: function() {
            // Enable button & show success message
        $("#btnSubmit").attr("disabled", false);
            $('#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");
        },
    }); //inserted a semi-colon here to end the Ajax function
} else {
//The error from your Ajax code will not signify if the user's answer is incorrect but this else block will allow you to append an error like you said in the comments
} //end of if else block
// I BELIEVE THE CURLY BRACE AND COMMA FOLLOWING THIS ARE NOT NEEDED
},

Upvotes: 1

Related Questions