jcadima
5/26/2017 - 4:21 PM

Recaptcha Ajax - Complete working demo

Recaptcha Ajax - Complete working demo

============================= the index file =============================

<?php include 'config.php'  ; ?>
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title></title>

 <script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>

<body>

<form action="" method="POST" id="leadform">
    <input type="text" id="name" name="name" value="" placeholder="Name">
    <input type="text" id="email" name="email" value="" placeholder="Email">
    <div><textarea type="text" id="message" name="message" placeholder="Message"></textarea></div>
    <div class="g-recaptcha" data-sitekey="6LeT7h8UAAAAALq7qjy90QTcjphFpAtg3oW6zEcT"></div>
    <input type="submit" name="submit" value="SUBMIT">
</form>

<div id="result" style="display:none;"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

<script>
$(document).ready(function() {
	$("#leadform").submit(function(event) {
	    /* Stop form from submitting normally */
	    event.preventDefault();
	    /* Get from elements values */
	    var name = $('#name').val();
	    var email = $('#email').val();
	    var message = $('#message').val();
	    var g_recaptcha_response  = $('#g-recaptcha-response').val();

	    /* Clear result div*/
	    $("#result").html('');
	    
        ajaxRequest = $.ajax({
            url: "process_ajax.php",
            type: "post",
            data: {name:name,email:email,message:message, g_recaptcha_response: g_recaptcha_response }
        });

        /*  request cab be abort by ajaxRequest.abort() */

        ajaxRequest.done(function (response, textStatus, jqXHR){
          // show successfully for submit message
          console.log("SUCCESS") ;
          $('#result').show() ;
          $("#result").html(response);
        });

        /* On failure of request this function will be called  */
        ajaxRequest.fail(function (response){
        // show error
        console.log("ERROR") ;
        $("#result").html('Error found trying to submit the form: ' + response );
        });

	});

}); // end document ready
</script>

</body>

</html>



=================  the process ajax file process_ajax.php =====================

<?php
// require 'Recaptcha.php';
// if ( ! class_exists('Recaptcha') ) die('Class Recaptcha not found') ; 

require_once dirname(__FILE__) . '/Recaptcha.php';

$name  = $_POST['name'] ;
$email  = $_POST['email'] ;
$message  = $_POST['message'] ;
$recaptcha = $_POST['g_recaptcha_response'];

$recobj = new Recaptcha();
$response = $recobj->verifyResponse($recaptcha);

if( isset($response['success']) && $response['success'] != true )  {
	echo "An Error Occured and Error code is :".$response['error-codes'];
}
else {
	echo 'Correct Recaptcha<br>
	 Name: ' . $name . '<br>' .
	'Email: ' . $email . '<br>'  .
	'Message: ' . $message . '<br>'  .
	'recaptcha value: ' . $recaptcha ;
}

?>

===================  the Recaptcha class: Recaptcha.php =====================

<?php
class Recaptcha {
	
	public function __construct(){
		// retrieve config array values
        $this->config = require('config.php');
    }

	public function verifyResponse($recaptcha){
		
		$remoteIp = $this->getIPAddress();

		// Discard empty solution submissions and return
		if (empty($recaptcha)) {
			return array(
				'success'     => false,
				'error-codes' => 'Recaptcha is required',
			);
		}

		// get a JSON response
		$jsonresponse = $this->getJSONResponse(
			array(
				'secret'   => $this->config['secret-key'],
				'remoteip' => $remoteIp,
				'response' => $recaptcha,
			)
		);

		// decoded JSON reCAPTCHA server response
		$responses = json_decode($jsonresponse, true);

		// Set array keys for success/failure
		if ( isset($responses['success']) and $responses['success'] == true ) {
			$status = true;
		} else {
			$status = false;
			$error = (isset($responses['error-codes'])) ? $responses['error-codes']
				: 'invalid-input-response';
		}

		// return the status and if error-codes (if any)
		return array(
			'success'     => $status,
			'error-codes' => (isset($error)) ? $error : null,
		);
	}

	private function getJSONResponse($data){
		// we use http_build_query to generate a URL encoded query string , ex:
		// https://www.google.com/recaptcha/api/siteverify?secret=".$this->secret. "&response=".$response;
		// remoteip is optional, but its passed if needed by our app requirements
		$url = 'https://www.google.com/recaptcha/api/siteverify?'.http_build_query($data);
		$response = file_get_contents($url);

		return $response;
	}

	private function getIPAddress(){
		if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
			$ip = $_SERVER['HTTP_CLIENT_IP'];
		} 
		elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))  	{
			$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
		} 
		else  {
			$ip = $_SERVER['REMOTE_ADDR'];
		}
		
		return $ip;
	}

}

?>


===================== the config file: config.php  =========================

<?php
// these will work on Localhost
return [
	'client-key' => '6LeT7h8UAAAAALq7qjy90QTcjphFpAtg3oW6zEcT',
	'secret-key' => '6LeT7h8UAAAAAOoLSh0t6tPgv8D3hCMUeJN5FxRY'
];

?>