Get access to an awe-inspiring collection Of 87 Beautiful Wordpress themes for the price of one Get it now Ad

How to build a working Bootstrap contact form

Published: 16.5.2016 | Last update: 15.3.2017

Today I would like to show you how to easily build a working HTML contact form using a Bootstrap framework and AJAX with PHP. You will need some basic knowledge of HTML, CSS and Bootstrap CSS framework

In the tutorial, I will walk you through the parts that will show you how to code the contact form in HTML, style it a bit and add real-time validation to the required fields. 

Then I will show you how the data is handled and email sent in the PHP script.

As the last thing, you will learn how little JavaScript magic (we will use jQuery) is needed to submit the form via AJAX without reloading the page itself. This will be really handy when you have the contact form on the one-page web and you don't want to reload the whole page.

The result of this tutorial will be working responsive contact form with fields validation and with some basic CSS styling. It will look like on the picture below.

Contact Form in Bootstrap

Demo Download files

Many of my free Bootstrap templates come with a contact form, so you can use this solution to make them work too.

HTML template

Let's start with the main HTML layout of our contact form page.

There should not be anything tricky for you, so just a few words about it:

  • In the head, we include the Bootstrap stylesheet, Lato from Google fonts, and a local custom.css stylesheet. 
  • before the <body> closing tag we include jQuery, Bootstrap scripts and local contact.js file which will handle AJAX sending of the form
  • for Bootstrap, jQuery and a Font I used their CDN versions. If you test the scripts without an internet connection, don't forget to include their local versions.

 

<html>
    <head>
        <title>Contact Form Tutorial by Bootstrapious.com</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
        <link href='https://fonts.googleapis.com/css?family=Lato:300,400,700' rel='stylesheet' type='text/css'>
        <link href='custom.css' rel='stylesheet' type='text/css'>
    </head>
    <body>

        <div class="container">

            <div class="row">

                <div class="col-lg-8 col-lg-offset-2">

                    <h1>Contact form Tutorial from <a href="http://bootstrapious.com">Bootstrapious.com</a></h1>

                    <p class="lead">This is a demo for our tutorial dedicated to crafting working Bootstrap contact form with PHP and AJAX background.</p>


                    <form></form> 

                </div>

            </div>

        </div>

        <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
        <script src="validator.js"></script>
        <script src="contact.js"></script>
    </body>
</html>

The form HTML code

As we have the main layout ready, we can replace the <form></form> in our HTML code with our fancy Bootstrap Contact form itself.

At the end form should look like this:

<form id="contact-form" method="post" action="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="Message for me *" 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">
                <input type="submit" class="btn btn-success btn-send" value="Send message">
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                <p class="text-muted"><strong>*</strong> These fields are required. Contact form template by <a href="http://bootstrapious.com" target="_blank">Bootstrapious</a>.</p>
            </div>
        </div>
    </div>

</form>

Well, this looks a bit more interesting already, so let's have a look at all the pieces of the puzzle now:

  • We will send the contact form values via POST to the PHP script called contact.php. As there could be more forms on the page (search etc.), we mark our form with #contact-form id to address it correctly. There is also empty div .messages that will serve us to display the success or error message after sending the form via AJAX.
  • Standard Bootstrap forms markup is used - rows, columns, form groups. Form groups are Bootstrap helpers that take care of the appropriate spacing in the form.
  • For the validation of the fields, we will be using the great Bootstrap validator. Validation rules are specified on form inputs via the standard HTML5 attributes, in our case these are required and type="email".
  • We will be using custom error messages for each field, passed to the script in the data-error attribute.
  • To display the possible errors, there is a <div class="help-block with-errors"></div> block added to each form-group
  • Also, note type="email" and type="tel" inputs that will enhance the user experience, especially if using the mobile device. 

This should basically do for the HTML part of the form and we can move on to the PHP script.

PHP script

The PHP script that will handle the email sending is located in the contact.php file.

In the first part of the script, we configure the basic variables we will need. These are:

  • $from - the email address that will be in the From field of the email. Important: To avoid being marked as spam or even to be able to send it from your web host, use email on your domain: so if you will be using the form on mygreatsite.com, use 'info@mygreatsite.com' in this variable. Make also sure that this email actually exists.
  • $sendTo - the email address that will receive the email with the output of the form. Can be your personal address or can be same as the address as in $from variable. Make sure this email exists.
  • $subject - the subject of the email
  • $fields - an array of form control names and their English counterparts. If we have input called name <input name="name">, we can call it in our email e.g. Customer Name like this: 'name' => 'Customer Name'
  • $okMessage - the message text displayed on the web page when the message is successfully sent
  • $errorMessage - the text of the message displayed in case of an error

We will wrap the whole code block in the try/catch block which will catch all the possible errors. 

The code works as follows:

  1. we start building the email message content in $emailText
  2. we iterate through the $_POST ( the array containing all the values sent through the POST request)
  3. if we find out that the key of the item from $_POST array also exists in our $fields array, we include it to the text of the message in $emailText 
  4. we send the email via PHP internal mail() function. We add some important headers to the email using the $headers array (encoding, from header, reply to, etc.)
  5. we create $responseArray variable to be sent as JSON response back to our index.html to be handled by our JavaScript function 
  6. if the request came via AJAX (you check this in PHP using the condition if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')) we send the JSON response, if not we simply display the message (this should be a rare case - e.g. for users with disabled JavaSript)
<?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';

// let's do the sending

try
{
    $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'];
}

Technical requirements for the PHP are:

  • PHP >= 5.3
  • email server setup

A little bit of Javascript

The JavaScript part of this tutorial will handle the validation of the form and its sending via AJAX. We will save it to contact.js.

First, we will run the validator script on our contact form.

Then, we will add some JavaScript that will help us with the submitting of the form via AJAX request.

It works like this:

  1. When the form with the #contact-form id is submitted, we make the POST request to the contact.php script.
  2. On request's success, we work with the JSON object that is returned by the PHP script. The object has only two properties - type and message
  3. We use type and message to construct the message visible for the user - in case of error we display alert-danger, in case of success we display alert-success
  4. We display the message, reset form inputs and return false; to prevent the usual form submitting
$(function () {

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

    $('#contact-form').on('submit', function (e) {
        if (!e.isDefaultPrevented()) {
            var url = "contact.php";

            $.ajax({
                type: "POST",
                url: url,
                data: $(this).serialize(),
                success: function (data)
                {
                    var messageAlert = 'alert-' + data.type;
                    var messageText = data.message;

                    var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + messageText + '</div>';
                    if (messageAlert && messageText) {
                        $('#contact-form').find('.messages').html(alertBox);
                        $('#contact-form')[0].reset();
                    }
                }
            });
            return false;
        }
    })
});

Conclusion

So, that's all for today. You should have a great contact form working and ready to be implemented on your website.

As always, there could be further modifications done as e.g. Captcha implementation - I will try to include some of these in one of the next updates of this tutorial. I have created a tutorial covering this topic: check out Bootstrap & ReCaptcha form tutorial. If you haven't done that already, have a look at my free Bootstrap themes too.

If you liked the article - let your friends know about it - remember: sharing is caring :)

Thanks!

Note

Development on your computer

If you want to develop the form on your computer, you will need a local server with PHP support. One of the most common solutions is e.g. XAMPP (I use it myself), but there are many more.

The localhost solution, be it XAMPP or similar, will most probably not have any working mail server included. To be able to debug/develop the emails, there are utilities, that simulate the mail server behaviour and instead of sending the email, they save the output/source code of the email to your hard drive. If you are using XAMPP, it comes with the utility called mailtodisk and emails will be saved in xamppfolder/mailoutput. One of the similar solutions can be e.g. MailCatcher, but I don't have any personal experience with it.

To be able to send real email messages, you will need to put the script/page to the internet. To order great web hosting, have a look at iPage - one of the most reliable web hosts on the market. If you are new to them, to will also give you 80% off + many extras.

Hi, I'm Ondrej, creator of Bootstrapious. I have published Bootstrap tutorials and freebies here since 2015.

Would you like to choose a topic for a next tutorial or a type of the next freebie? Do you need a consultation or would you like to get an exposure on the Bootstrapious website?

Become one of Bootstrapious' patrons on Patreon and get one of the many great rewards I offer there.

Thanks for stopping by and have a great day ;)

Ondrej, Bootstrapious

You might also like one of our Free Themes

Universal - Business & E-commerce Template

Universal is clean and stylish universal website template built with Bootstrap 3.3. It stands out…

View theme

Italiano - Restaurant or Café Template

Italiano is my free Bootstrap HTML responsive template. You can use it to build an elegant website…

View theme

Single product e-commerce template
PREMIUM

Single product e-commerce template

T-Shirt store is a versatile Bootstrap e-commerce template. It's great for selling a single…

View theme

Comments

Comments automatically close after 120 days.

Although I would like to help everyone getting their websites running, I simply can't as my time is really limited.

If you need a consultation or support, I provide a dedicated consulting to Bootstrapious Patrons - just choose a Dedicated support reward on my Patreon page and get in touch. Thank you for understanding and supporting Bootstrapious.

Share on Facebook Share on G+ Share on Twitter Share on LinkedIn