简体   繁体   中英

AJAX script alerts for contact form with PHP, Google reCAPTCHA, and SweetAlert

I am using an AJAX script to submit a basic contact form at the bottom of my HTML that uses Google reCAPTCHA. The html code is:

 <div class="col-md-6"> <form role="form" id="form" action="form.php" method="post"> <div class="form-group"> <label for="name">Your Name</label> <input type="text" class="form-control" id="name" name="name" placeholder="Enter name"> <span class="help-block" style="display: none;">Please enter your name.</span> <label for="exampleInputEmail1">Email address</label> <input type="email" class="form-control" id="email" name="email" placeholder="Enter email"> <span class="help-block" style="display: none;">Please enter a valid e-mail address.</span> <label for="exampleInputText1">Message</label> <textarea class="form-control" rows="3" id="message" name="message" placeholder="Enter message"></textarea> <span class="help-block" style="display: none;">Please enter a message.</span> </div> <div class="form-group"> <div class="g-recaptcha" data-sitekey="I HAVE REMOVED MY SITE KEY"></div> <span class="help-block" style="display: none;">Please check that you are not a robot.</span> </div> <button type="submit" id="Submit" data-loading-text="Sending..." class="btn btn-default">Submit</button> </form> </div> <!-- Placed at the end of the document so the pages load faster --> <script src="http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.2/modernizr.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script type="text/javascript" src="slick/slick.min.js"></script> <script src="assets/js/smoothscroll.js"></script> <script src="assets/js/jquery.stellar.min.js"></script> <script src="assets/js/fancybox/jquery.fancybox.js"></script> <script src="assets/js/main.js"></script> <script src="alert/sweetalert2.min.js"></script> <script src='https://www.google.com/recaptcha/api.js'></script> 

I have created a very basic php to email me the data entered into the form.

 <?php //include CSS Style Sheet echo "<link rel='stylesheet' type='text/css' href='alert/sweetalert2.css' />"; //include a javascript file echo "<script type='text/javascript' src='alert/sweetalert2.min.js'></script>"; // Define some constants define( "RECIPIENT_NAME", "Paul O'Shea" ); define( "RECIPIENT_EMAIL", "I HAVE REMOVED MY EMAIL" ); define( "EMAIL_SUBJECT", "Website Enquiry" ); $full_name;$email;$subject;$message;$captcha; if(isset($_POST['name'])){ $name=$_POST['name']; }if(isset($_POST['email'])){ $email=$_POST['email']; }if(isset($_POST['message'])){ $message=$_POST['message']; }if(isset($_POST['g-recaptcha-response'])){ $captcha=$_POST['g-recaptcha-response']; } if(!$captcha){ echo '<script type="text/javascript">'; echo 'setTimeout(function () { swal("ERROR!","In order to avoid SPAM mail, you must confirm you are human. Please select IM NOT A ROBOT and complete the simple challenge","error");'; echo '}, 1000); </script>'; exit; } $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?I HAVE REMOVED MY SECRET KEYresponse=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']); if($response.success==false) { echo "<script type=\\"text/javascript\\">alert('Message Failed. Please try again'); location.href='index.html#contact';</script>"; }else { // If all values exist, send the email if ( $name && $email && $message ) { $recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">"; $headers = "From: " . $name . " <" . $email . ">"; $success = mail( $recipient, EMAIL_SUBJECT, $message, $headers ); } echo "<script type=\\"text/javascript\\">alert('Thanks for your enquiry! Your message has been sent to Paul and he will be in touch within 48hrs'); location.href='index.html#contact';</script>"; } ?> 

The PHP has 3 alerts within it:

  1. reCAPTCHA has not been run.

  2. If reCAPTCHA fails.

  3. Success message.

These PHP alerts work if i bypass the AJAX script, (however open a blank form.php) but don't work at all when I use the AJAX script. Therefore I get a success alert from the AJAX script - even if the reCAPTCHA has not been completed - and the form data has not been emailed.

This is my AJAX script:

 <script type="text/javascript"> var frm = $('#form'); frm.submit(function (ev) { $.ajax({ type: frm.attr('method'), url: frm.attr('action'), data: frm.serialize(), success: function (data) { swal( 'Thanks for your enquiry!', 'Your message has been sent. Paul will be in contact soon.', 'success' ); } }); ev.preventDefault(); }); </script> 

This gives the desired result, the email is sent, and the nice alert is shown over the original page, and when closed returns to original page. However, none of the alerts referenced in form.PHP are displayed. If user forgets to run reCaptcha - the same success alert is shown - even though there message will not be emailed.

Can anyone help me add the PHP alerts to the AJAX javascript? I tried copy and paste the same code - but am a little unsure of the appropriate way to format the code. Any help greatly appreciated! Thanks!

I would remove the <script> responses from your php script and instead use plain text, then I'd go with an AJAX approach of form submission.

There are plenty of examples using this ( recommended in my opinion ) approach, check the following two:

Using just jQuery: jQuery Ajax POST example with PHP

jQuery AJAX submit form

Another approach is to create one file with both your HTML and php in it, and don't redirect your form post to another page but to itself. However, this would invoke a page refresh.

Check the following example:

Refresh page after form submitting - Check 1st Answer

Keywords for further searching: post form, ajax, php, jquery, jquery form plugin malsup

EDIT 1 - Code

HTML/JS:

    <div class="col-md-6">
      <form role="form" id="form" action="form.php" method="post">
        <div class="form-group">
          <label for="name">Your Name</label>
          <input type="text" class="form-control" id="name" name="name" placeholder="Enter name">

          <span class="help-block" style="display: none;">Please enter your name.</span>

          <label for="exampleInputEmail1">Email address</label>
          <input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
          <span class="help-block" style="display: none;">Please enter a valid e-mail address.</span>

          <label for="exampleInputText1">Message</label>
          <textarea class="form-control" rows="3" id="message" name="message" placeholder="Enter message"></textarea>

          <span class="help-block" style="display: none;">Please enter a message.</span>
        </div>
        <div class="form-group">
          <div class="g-recaptcha" data-sitekey="I HAVE REMOVED MY SITE KEY"></div>
          <span class="help-block" style="display: none;">Please check that you are not a robot.</span>
        </div>
        <button type="submit" id="Submit" data-loading-text="Sending..." class="btn btn-default">Submit</button>
      </form>

    </div>
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.2/modernizr.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script type="text/javascript" src="slick/slick.min.js"></script>
    <script src="assets/js/smoothscroll.js"></script>
    <script src="assets/js/jquery.stellar.min.js"></script>
    <script src="assets/js/fancybox/jquery.fancybox.js"></script>
    <script src="assets/js/main.js"></script>
    <script src="alert/sweetalert2.min.js"></script>
    <script src='https://www.google.com/recaptcha/api.js'></script>
    <script type="text/javascript">

    $(document).ready(function(e) {
        var frm = $('#form');
        frm.submit(function (ev) {
            $.ajax({
                type: frm.attr('method'),
                url: frm.attr('action'),
                data: frm.serialize(),
                success: function (data) {
                    if (data == "error")
                    {
                        swal("ERROR!","In order to avoid SPAM mail, you must confirm you are human. Please select IM NOT A ROBOT and complete the simple challenge","error");
                    }
                    else if (data == "fail")
                    {
                        swal("Failed", "Message Failed. Please try again!", "error");                       
                        location.href='index.html#contact';
                    }
                    else if (data == "success")
                    {
                        swal("Thanks for your enquiry!", "Your message has been sent to Paul and he will be in touch within 48hrs", "success"); 
                        location.href='index.html#contact';
                    }
                    else
                    {
                        swal("Something went wrong!", data, "error");
                    }
                }
            });

            ev.preventDefault();
        });
    });
</script>

Your php script:

<?php
// Define some constants
define( "RECIPIENT_NAME", "Paul O'Shea" );
define( "RECIPIENT_EMAIL", "I HAVE REMOVED MY EMAIL" );
define( "EMAIL_SUBJECT", "Website Enquiry" );

$full_name;$email;$subject;$message;$captcha;
if(isset($_POST['name']))
{
    $name=$_POST['name'];
    if($name != filter_var($name, FILTER_SANITIZE_STRING))
    {
        echo "Name is not valid!";
        exit(); // or exit w/e you please
    }
}
else
{
    echo "Name field is required!";
    exit(); // or exit w/e you please
}
if(isset($_POST['email']))
{
    $email=$_POST['email'];
    if(! filter_var($email, FILTER_VALIDATE_EMAIL))
    {
        echo "Email is not valid!";
        exit(); // or exit w/e you please
    }
}
else
{
    echo "Email field is required!";
    exit(); // or exit w/e you please
}

if(isset($_POST['message']))
{
    $message=$_POST['message'];
    if($message != filter_var($message, FILTER_SANITIZE_STRING))
    {
        echo "Name is not valid!";
        exit(); // or exit w/e you please
    }
}
else
{
    echo "Message field is required!";
    exit(); // or exit w/e you please
}

if(isset($_POST['g-recaptcha-response']))
{
    $captcha=$_POST['g-recaptcha-response'];
}

if(!$captcha)
{
    echo 'error';
    exit();
}

$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?I HAVE REMOVED MY SECRET KEYresponse=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);

if($response.success==false)
{
    echo 'fail';
    // No need to exit() here, code ends after this anyway
}
else
{
    // If all values exist, send the email
    if ( $name && $email && $message ) 
    {
        $recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
        $headers = "From: " . $name . " <" . $email . ">";
        $success = mail( $recipient, EMAIL_SUBJECT, $message, $headers );
        echo "success";
    }
    else
    {
        echo "Name, email and message are required!";
    }
    // No need to exit() here, code ends after this anyway
}
?>

EDIT 2 - Validation (Added in code as well)

You can use php's filter_var function with the available filters to validate your input. Likewise, if a validation fails you can echo and exit accordingly with a message like echo 'other' which would invoke the last if case at the JS above (just fix the title perhaps to something like "Input error" or "Invalid input").

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM