Bootstrap Contact Form with Captcha using Ajax and PHP

Contact Form is an important part of any website to gather feedback, questions etc. about website from readers. So in this tutorial you will learn how to create beautiful Bootstrap contact form with Captcha using Ajax and PHP. The tutorial covered in easy steps with live to create contact form using Bootstrap framework with Google's ReCaptcha. The form submission handled with jQuery Ajax without page reload and contact detail email send through PHP script after Captcha validation at server side.



As we have covered this tutorial with live demo to create Bootstrap contact form with Captcha using Ajax and PHP, so the file structure for this example is following.


  • index.php

  • ajax_contact.js

  • contact_process.php





Steps1: Include Bootstrap and jQuery Files
As we will design conatct form with Bootstrap Framework, so first we will include Bootstrap, jQuery files.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>



Steps2: Register Google's ReCaptcha
As in this tutorial, we will create contact form with captcha, so we will need to register website on Google's ReCaptcha to use Captcha in contact form. The Site key and Secret key provided after registering website on Google's ReCaptcha to validate Captcha from contact form. We also need to include Javascript file provided by Google's ReCaptcha.

<script src='https://www.google.com/recaptcha/api.js'></script>

We need to use following HTML with site key to display Google Captcha in contact form.

<div class="g-recaptcha" data-sitekey="6LfwyDEUAAAAAHwP7cx_q_Rdk4UN1dJ8S1XR9A04"></div>



Steps3: Design Bootstrap Contact Form
Now in index.php, we will disign Bootstrap contact form with captcha.
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<h2>Bootstrap Contact Form with Captcha using PHP & Ajax</h2>
<form id="contact_form" method="post" action="process_contact.php" role="form">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_name">Firstname *</label>
<input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your firstname *" required="required" data-error="Firstname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_lastname">Lastname *</label>
<input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Please enter your lastname *" required="required" data-error="Lastname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_email">Email *</label>
<input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email *" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_phone">Phone</label>
<input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Please enter your phone">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="form_message">Message *</label>
<textarea id="form_message" name="message" class="form-control" placeholder="Please enter message *" rows="4" required="required" data-error="Please,leave us a message."></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<div class="g-recaptcha" data-sitekey="6LfwyDEUAAAAAHwP7cx_q_Rdk4UN1dJ8S1XR9A04"></div>
</div>
</div>
<div class="col-md-12">
<input type="submit" class="btn btn-success btn-send" value="Send message">
</div>
</div>
</div>
</form>
</div>
</div>
</div>




Steps4: Handle jQuery Ajax Contact Form Submit
In ajax_contact.js, we will handle contact form submit with jQuery Ajax to not reload page when submit form. Send Ajax request to process_contact.php to send contact page detail email with cCaptach validation. Display form submit success or fail message.
$( document ).ready(function() {
$('#contact_form').on('submit', function (e) {
$.ajax({
type: "POST",
url: "process_contact.php",
data: $(this).serialize(),
success: function (response) {
var message_type = 'alert-' + response.type;
var message_text = response.message;
var message = '<div class="alert ' + message_type + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + message_text + '</div>';
if (message_type && message_text) {
$('#contact_form').find('.messages').html(message);
$('#contact_form')[0].reset();
grecaptcha.reset();
}
}
});
return false;
})
});



Steps5: Send Contact Form Details
Now finally in process_contact.php, we will compose contact details Form Post values to design message and send email. We will also check Captach validation at server end using Google ReCaptach secret key.
<?php
require('recaptcha/src/autoload.php');
$from_email = 'example@domain.com';
$send_to_email = 'example@domain.com';
$subject = 'New message from contact form';
$form_fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message');
$mail_send_suceess = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$mail_send_failed = 'There was an error while submitting the form. Please try again later';
$recaptcha_secret_key = '';
try {
if (!empty($_POST)) {
if (!isset($_POST['g-recaptcha-response'])) {
throw new \Exception('ReCaptcha is not set.');
}
$recaptcha = new \ReCaptcha\ReCaptcha($recaptcha_secret_key, new \ReCaptcha\RequestMethod\CurlPost());
$response = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if (!$response->isSuccess()) {
throw new \Exception('ReCaptcha was not validated.');
}
$message_body = "You have new message from contact form\n=============================\n";
foreach ($_POST as $key => $value) {
if (isset($form_fields[$key])) {
$message_body .= "$form_fields[$key]: $value\n";
}
}
$headers = array('Content-Type: text/plain; charset="UTF-8";',
'From: ' . $from_email,
'Reply-To: ' . $from_email,
'Return-Path: ' . $from_email,
);
mail($send_to_email, $subject, $message_body, implode("\n", $headers));
$responseArray = array('type' => 'success', 'message' => $mail_send_suceess);
}
} catch (\Exception $e) {
$responseArray = array('type' => 'danger', 'message' => $mail_send_failed);
}
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'];
}
?>


You can view the live demo from the Demo link and can download the script from the Download link below.
Demo [sociallocker]Download[/sociallocker]

Komentar

  1. Hi, thanks for this tutorial and files, i have made a test and have the message :
    "There was an error while submitting the form. Please try again later"

    I have registred the domain, and put the key site in process_contact.php and index.php

    Thanks for the help

    BalasHapus
  2. ok found it's the secret key i have to put :)

    BalasHapus
  3. hI
    If i use the downloaded files everything works well. If i copy the contact form code in my index i get the following not found Error after clicking on send : "contact.php was not found on this server."

    Thank you for help

    BalasHapus
  4. I have just check source code and its working fine. May be you have changed Form action Php script name and it should be available in your working directory. please check it.

    BalasHapus

Posting Komentar

Postingan Populer