0 votes
389 views
by (270 points)

Hi, 

I am integrated google captcha in bootstrap website code i get from here http://bit.ly/2x8LL3Z

its working fine. How can i set a redirect webpage to thankyoupage after form submission.

PHP Code is given below for reference 

<?php
// require ReCaptcha class
require('recaptcha-master/src/autoload.php');

// configure
$from = 'domain@xyz.com;
$sendTo = 'domain@xyz.com';
$subject = 'New message from contact form';
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'message' =>'Message'); // array variable name => Text to appear in the email
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
$recaptchaSecret = 'CODE GOES HERE';
// let's do the sending

try
{
    if (!empty($_POST)) {

        // validate the ReCaptcha, if something is wrong, we throw an Exception, 
        // i.e. code stops executing and goes to catch() block
        
        if (!isset($_POST['g-recaptcha-response'])) {
            throw new \Exception('ReCaptcha is not set.');
        }

        // do not forget to enter your secret key in the config above 
        // from https://www.google.com/recaptcha/admin
        
        $recaptcha = new \ReCaptcha\ReCaptcha($recaptchaSecret, new \ReCaptcha\RequestMethod\CurlPost());
        
        // we validate the ReCaptcha field together with the user's IP address
        
        $response = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);

        if (!$response->isSuccess()) {
            throw new \Exception('ReCaptcha was not validated.');
        }
        
        // everything went well, we can compose the message, as usually
        
        $emailText = "You have new message from contact form\n=============================\n";

        foreach ($_POST as $key => $value) {

            if (isset($fields[$key])) {
                $emailText .= "$fields[$key]: $value\n";
            }
        }
        

        $headers = array('Content-Type: text/plain; charset="UTF-8";',
            'From: ' . $from,
            'Reply-To: ' . $from,
            'Return-Path: ' . $from,
        );

        mail($sendTo, $subject, $emailText, implode("\n", $headers));

        $responseArray = array('type' => 'success', 'message' => $okMessage);
    }
}
catch (\Exception $e)
{
    $responseArray = array('type' => 'danger', 'message' => $errorMessage);
}

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $encoded = json_encode($responseArray);

    header('Content-Type: application/json');

    echo $encoded;
}
else {
    echo $responseArray['message'];
}

1 Answer

+1 vote
by (9.3k points)
edited by

Procedure to redirect the page after successful submission or even on fail.

1. Remove following snippet from contact.js

// when the form is submitted
// delete ALL OF THESE
$('#contact-form').on('submit', function (e) {
     ....
})

2. Then, at the end of your contact.php, replace the following snippet,

// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
   ...
}
// else just display the message
else {
   ...
}

with this new snippet

if ($responseArray['message'] == 'success') {
    // success redirect

    header('Location: http://www.example.com/success.html');
}
else {
    //error redirect
    header('Location: http://www.example.com/error.html');
}

It will work..! Browser like Chrome may block the redirect request if proper Access-Control-Allow-Origin header not implemented.

Update: For more convenience, I am submitting the full ready to use a snippet of files needs to be changed. However, remember to replace values of recaptcha secret key, email address with own.

1. contact.js

$(function () {

    $('#contact-form').validator();

    
});

2. contact.php

<?php
// require ReCaptcha class
require('recaptcha-master/src/autoload.php');

// configure
$from = 'Demo contact form <demo@domain.com>';
$sendTo = 'Demo contact form <demo@domain.com>';
$subject = 'New message from contact form';
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message'); // array variable name => Text to appear in the email
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
$recaptchaSecret = 'YOUR_SECRET_KEY';

// let's do the sending

try
{
    if (!empty($_POST)) {

        // validate the ReCaptcha, if something is wrong, we throw an Exception, 
        // i.e. code stops executing and goes to catch() block
        
        if (!isset($_POST['g-recaptcha-response'])) {
            throw new \Exception('ReCaptcha is not set.');
        }

        // do not forget to enter your secret key in the config above 
        // from https://www.google.com/recaptcha/admin
        
        $recaptcha = new \ReCaptcha\ReCaptcha($recaptchaSecret, new \ReCaptcha\RequestMethod\CurlPost());
        
        // we validate the ReCaptcha field together with the user's IP address
        
        $response = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);


        if (!$response->isSuccess()) {
            throw new \Exception('ReCaptcha was not validated.');
        }
        
        // everything went well, we can compose the message, as usually
        
        $emailText = "You have new message from contact form\n=============================\n";

        foreach ($_POST as $key => $value) {

            if (isset($fields[$key])) {
                $emailText .= "$fields[$key]: $value\n";
            }
        }
        

        $headers = array('Content-Type: text/plain; charset="UTF-8";',
            'From: ' . $from,
            'Reply-To: ' . $from,
            'Return-Path: ' . $from,
        );

        mail($sendTo, $subject, $emailText, implode("\n", $headers));

        $responseArray = array('type' => 'success', 'message' => $okMessage);
    }
}
catch (\Exception $e)
{
    $responseArray = array('type' => 'danger', 'message' => $errorMessage);
}

if ($responseArray['message'] == 'success') {
    // success redirect

    header('Location: http://www.example.com/success.html');
}
else {
    //error redirect
    header('Location: http://www.example.com/error.html');
}
by (270 points)
thanks its working
Welcome to DoubtSolver Q&A, where you can ask doubts and receive solutions from other members of the community.

242 questions

229 answers

25 comments

2.4k users

Top Users Sep 2019
  1. vijendra saini

    580 Points

  2. Antareep Ray

    510 Points

  3. Nikhil Rastogi

    460 Points

  4. Naisargi

    300 Points

  5. manojb05

    270 Points

  6. Sneha

    260 Points

  7. Adarsh kumar

    230 Points

  8. Kjithinsai

    210 Points

  9. jithin

    210 Points

  10. Mary.Z

    200 Points

Categories

...