Unlimited Wordpress themes, plugins, graphics & courses! Unlimited asset downloads! From $16.50/m Advertisement # Building a Bootstrap Contact Form Using PHP and AJAX Difficulty:BeginnerLength:LongLanguages: In this tutorial I’ll go over the steps to create a working contact form, utilising the ever popular front-end framework Bootstrap, in combination with AJAX and PHP. From there we can explore some additional features such as some fancy CSS animation with animate.css, further validation in JavaScript and refining the user experience with asynchronous content. At the time of writing Bootstrap 3.3.5 is the most current version, and it’s worth mentioning that we are using a default build of Bootstrap (with a 12 column layout) for this tutorial. When following along make sure you use the latest snippets and code structures as outlined by the Bootstrap documentation ### Looking for a Quick Solution? If you're looking for a quick solution, there's a great collection of PHP form scripts over at Envato Market. Starting from just a few dollars, they're a great way to get this functionality implemented quickly (with loads of powerful features to boot!) You can also get an Envato Studio service provider to handle the whole thing for you. For example, you can get a slick AJAX PHP contact form with Google's No Captcha reCaptcha created and added to your site for just$45.

File and Folder Structure

Firstly, we want to create a root directory and include the following files and folders:

We will need to include some front-end libraries to help us out, so go ahead and download (or externally reference) the following:

Drop in these libraries, so the file structure becomes:

## Building the Basics of the Form

Opening up the index.html file, copy the following HTML base structure:

This is our basic html template in which we will build the contents for the form. You can see we have linked all the necessary CSS and JavaScript files (note we don’t actually need bootstrap.js for this particular example). We have included a viewport meta tag to help with our media queries within Bootstrap. The JavaScript has been placed at the bottom of the file to help deliver the core content first.

Within our body tag, we have included a div with a class of col-sm-6 col-sm-offset-3. This basically means within our sm (small) viewport and above we wish to display a column of 50% width (there are a maximum of 12 columns). The col-sm-offset-3 class represents a margin left of 25%, thus producing a layout that is half the available screen viewport and horizontally centred. From here we have included an h3 and started the basics of our form. Make sure to apply an ID to this form so we can attach a jQuery event to this later on.

### No Guts, No Glory

Building the guts of the form we can copy/paste or write the following code within the <form></form> tags:

This is all of the input fields and buttons the user will interactive with. The initial div with the assigned class of row is classic Bootstrap syntax, representing a horizontal grouping of col elements. Columns within Bootstrap create padding or gutters–adding a row around these will remove the padding on the left and right helping them fit perfectly within their container.

We have created two columns with the col-sm-6 class (50%) which we will use to split our form up. Within the first col-sm-6 we have created a label and field for name, the second is for email. Each of these include a label with an appropriate for attribute so it can target the associated field. Each of these columns includes a form-group that semantically groups the label and field together and applies a small margin to the bottom.

### Typography

Bootstrap allows you to use typography classes from H1-H6. These classeshelp us style inline elements without adding extra margins or creating block elements. We have utilised an H4 to quickly style these labels making them large and clear.

The form-control class applied to each input enables it to span the entire length of the container (width 100%). It also applies various styling to help build an easy to read form element (larger height, flat border etc).

After these columns we include the message body. Again, we wrap this within a form-group and apply similar styles to our label and text area as we did before.

### The Call to Action

Finally we include the submit button. Bootstrap has a number of classes for various button and typography colours/states. We have opted to use the “success” button (btn-success) which is, by default, green. Additionally we need to apply the base btn class to reset the basic button features (border, padding, text-align, font-weight). We applied a btn-lg class which makes it a large button and finally a pull-right class which floats this button right.

After our button we have included a div with the id of #msgSubmit and applied the following classes: “h3 text-center hidden”. The h3 helps create a larger heading, text-center (you guessed it) sets the text-alignment to center, and finally we have set the hidden class which sets both display to none and visibility to hidden.

As you can see by viewing this in your preferred browser we have created a basic Bootstrap form. However it doesn’t actually do anything just yet. Our next step will be to create the function which takes the users’ inputs and sends them off asynchronously to our PHP mailer.

Opening up the scripts.js copy the following code:

This bit of code is a jQuery snippet which listens for a submit function on our #contactForm id (as set prior). Upon this function we parse an event variable that stores the submit form action to the function. The event.preventDeafult(); stops the form submitting as it would normally, which would refresh the page as no form action is set. Finally, it requests the submitForm(); function.

### submitForm();

Next we build the submitForm(); function as follows:

The three variables being set are grabbing the values of each input from the form and assigning them to a JavaScript variable to be used later.

We initiate an AJAX object within jQuery and set the parameters of type to post, URL to the PHP file location, the data we wish to send and the success call back function. The data includes all three concatenated variables with an associated id/label. The success call back function is called when the AJAX object successfully receives information back from the PHP script. The function grabs the returned text and checks to see if it equals the string “success”. If so it activates the final function of formSuccess.

The formSuccess function removes the hidden class from the #msgSubmit div that we applied earlier, thus revealing the text.

## Hooking it Into the PHP Mail Function

Finally, we need write a PHP script to receive the data and send our content via an inbuilt php mail function. Open process.php and include the following code:

Similar to the jQuery snippet earlier, we need to gather and store the variables we wish to use. From the post function we can gather the three input variables and assign them to similar variable names within PHP. The $EmailTo variable is a pre-defined email address that you can set in the script to send to your email upon form submission. $Subject is a string you wish to use as the email subject.

The email body is built loosely around the three variables established. Firstly setting some descriptive text such as “Name:”, then the variable, then a new line as determined by the /n (new line/line break). This is repeated and concatenated to the $body variable. To finally send the email we attach it within the mail function. Assigning the variable $success we include the email address it’s being sent to, the subject, the body and the from email.

To initiate the process of sending the email we can call it within an if statement. This also helps check to see if it was a success or not. If the mail function returned “true” the script will return “success”, if it failed it will return “invalid”.

This result will be returned to the AJAX object and handled back on the client side. The beauty of AJAX is that all of this is done asynchronously on the client end, enabling the user to continue to use the site while it’s being sent.

## Spit and Polish

Having covered the basic structure and functionality of our form in the first half of this tutorial, we will now get into the nitty gritty of providing user feedback through various additional features we can include. Specifically, we will cover form feedback through error handling both on the client side and server side.

Once again, to help with the process of establishing form validation, we will utilise some tools. These include:

Add these into the project as we did with Bootstrap and jQuery earlier. These tools will help provide feedback to the user when they submit the form. There are plenty of form validator tools and frameworks out there (including native HTML5 validation), but I have used the “Bootstrap Validator” as it nicely integrates with our current form.

The project structure should now look something like this:

## Validating Our Form

Let’s start by initiating the validator to check the form once we submit. Heading back into our scripts.js file we need to edit the first chunk of code that calls the submitForm() function when the form is submitted.

We need to update it to the following code:

This new bit of code checks to see if the Bootstrap Validator has found an issue and stopped it from processing. If it hasn't, we continue as per normal. We still need to prevent the default action (reloading the page) on successful submission of the form, so keep that in.

Clicking submit on our form when it’s not completely filled will now cause the empty fields to highlight in red showing what needs to be entered, it’s that easy!

In the process of adding this validation we have removed or prevented native HTML5 validation from taking place. We can add further context to our validation by including error messages. Bootstrap Validator has a nifty feature allowing for error messages for each input to display quite seamlessly. To add these we need to add some further HTML to provide a place for them to display.

Within each form-group under the input we should place the following html:

For example, here is the extra div added to the Name and Email fields:

Re-submitting the form now should now show the default error message when the fields are left blank “Please fill in this field.”. By adding a data-attribute to the input called “data-error” you can include a custom error message. For example:

There is a whole host of other features such as regular expression patterns that Bootstrap validator can accept. You can view more on Github.

Our client side validation is looking good; we have some nifty highlights occurring on empty fields. However, it would be good to add further animation to the form and add further messages letting the user know what’s occurring. Currently we have a "Message Submitted!" message appearing on success, but what about on an error?

To utilise existing code and make our scripts a bit more reusable we will modify the existing success message to accept errors too.

First things first, let’s remove the “Message Submitted!” text from the HTML and just leave an empty div:

We will now need to create a new function to handle the message status. Add this function to the bottom of the scripts.js

This function takes two arguments. valid will be a Boolean variable: if it’s true it will be a success message, false will be an error message. msg will be the message we will display in the div on screen.

Firstly the function checks to see if it’s dealing with a success or an error message by checking the value of valid. In either case it sets the class variable with the appropriate CSS classes (we need to re-include the h3 and text-center as we will be removing these by default later in the function.)

Note: we’re using some animate.css classes for the message success class. The tada animation will be played on success.

Finally, the function removes all classes from #msgSubmit (avoids clashing classes), then adds the classes set prior, and then adds the message text inside the div.

Inside our validator initiation we updated at the start of this section we can add the following function call inside the if statement when it’s equal to true.

Submitting the form with empty fields should now display the error message “Did you fill in the form properly?"

One last step for this new submitMSG function is to call it for when our form is successful. Update the formSuccess() function to the following:

Firstly we want to reset the form and clear the values on success, then we call our submitMSG function as before with a success message. Successfully submitting the form should now display the success message with a fancy animate.css tada animation effect.

### Shake it

What’s one more animation, right? Let’s add another animation to the entire form on error, a universal “shaking” animation should be good!

Create a new function just after formSuccess() and call it formError()

This function uses an approach found on the animate.css demo page that enables us to add an animation to an element and then re-call/add it again and again. CSS animations have a pesky issue in which once they are played once they tend to not play again, even when the class is removed and re-added. This function helps reset the classes on animation end, enabling you to re-add them again. When the user clicks submit on an incomplete form we want the shake animation to play. And if they submit it again when it’s still wrong it needs to play again.

We can call this formError() function above the submitMSG() function we created for an error message. For example:

Now when we submit an empty form it will shake to let the user know something has gone wrong.

## Moar Validation

All of this client side validation is good, however any user could disable these measures and submit the form with empty fields by editing the code within their browser. It’s always a good measure to do some server side validation, to capture anything that slips past.

Opening our process.php file we need to make some changes to this to check if the fields are empty; if they are not, send back a message to the front-end. We will create a variable called $errorMSG to capture our error messages and then include further $_POST validation.

This PHP checks to see if they are empty before setting them as the corresponding variable (replaces the existing code setting the variables from $_POST). If they are empty we then set a basic message to send back to the client. We can do a lot more than just validate the fields against being empty (If it’s too short/long check it against regular expressions etc.) in PHP and JavaScript. However, for the sake of simplicity, we will restrict it just to empty fields for now. We need to send back the error message to the initial AJAX call to be displayed in the browser. We will edit the if statement we created earlier at the bottom of the PHP file. In our if statement we also check to see if the $errorMSG is blank ( "" ) alongside the status of the inbuilt mail function we used on $success variable. In our else condition we have included a further check. This just checks to see if the error was a result of the $success failing, if so send back “Something went wrong :(“. Else we display the message that was compiled when we checked for empty values.

One last step is to accept this new message in our AJAX and display it on the form. We need to update the AJAX object within the scripts.js file as follows:

We have just updated the else condition which checks to see if text == success. In our else we have called the formError() function which will apply the shake animation and we have asked for the submitMSG() function to display the returned text back from the PHP. The text returned will either be “Something went wrong :(”  or the fields it received empty.

## Conclusion

Head on over to Github to take a look at the code in its entirety–we’ve done a lot!

Our form should now provide the user with some feedback on what fields are incorrect via solid validation. We provided contextual messages based upon the status and the returned message from PHP, and implemented an extra layer of validation on the server end to catch those who bypass the front end validation.

Overall you should now have a very sound contact form ready to be styled and integrated into your website. I hope you enjoyed this tutorial, please feel free to leave any questions or thoughts in the comments below!