Building a Bootstrap Contact Form Using PHP and AJAX


#1

Final product image
What You’ll Be Creating

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

[php]

Contact form using Bootstrap 3.3.4 "

Send me a message

</form>
[/php] 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.

the offset will push our DIV 25 from the right
No Guts, No Glory
Building the guts of the form we can copy/paste or write the following code within the tags:

[php]



Name



Email




Message


Submit
Message Submitted!
[/php] 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

Opening up the scripts.js copy the following code:

[php]$("#contactForm").submit(function(event){
// cancels the form submission
event.preventDefault();
submitForm();
});[/php]

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:

[php]function submitForm(){
// Initiate Variables With Form Content
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();

$.ajax({
    type: "POST",
    url: "php/form-process.php",
    data: "name=" + name + "&email=" + email + "&message=" + message,
    success : function(text){
        if (text == "success"){
            formSuccess();
        }
    }
});

}
function formSuccess(){
$( “#msgSubmit” ).removeClass( “hidden” );
}[/php]
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:

[php]<?php
$name = $_POST[“name”];
$email = $_POST[“email”];
$message = $_POST[“message”];

$EmailTo = "emailaddress@test.com";
$Subject = “New Message Received”;

// prepare email body text
$Body .= "Name: ";
$Body .= $name;
$Body .= “\n”;

$Body .= "Email: ";
$Body .= $email;
$Body .= “\n”;

$Body .= "Message: ";
$Body .= $message;
$Body .= “\n”;

// send email
$success = mail($EmailTo, $Subject, $Body, “From:”.$email);

// redirect to success page
if ($success){
echo “success”;
}else{
echo “invalid”;
}

?>[/php]
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:

Animate.css
Bootstrap Validator
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:

Bootstrap-Form:
├── css/
├── bootstrap.min.css
├── animate.css
├── images/
├── js/
├── scripts.js
├── bootstrap.js
├── jquery-1.11.2.min.js
├── validator.min.js
├── php/
├── process.php
├── index.html
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:

[php]$("#contactForm").validator().on(“submit”, function (event) {
if (event.isDefaultPrevented()) {
// handle the invalid form…
} else {
// everything looks good!
event.preventDefault();
submitForm();
}
});[/php]
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:

[php]

[/php]
For example, here is the extra div added to the Name and Email fields:

[php]



Name




Email


[/php] 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:

[php][/php]

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

Adding Feedback Animation

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:

[php]

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

[php]function submitMSG(valid, msg){
var msgClasses;
if(valid){
msgClasses = “h3 text-center tada animated text-success”;
} else {
msgClasses = “h3 text-center text-danger”;
}
$("#msgSubmit").removeClass().addClass(msgClasses).text(msg);
}[/php]

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.

[php]submitMSG(false, “Did you fill in the form properly?”);[/php]
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:

[php]$("#contactForm")[0].reset();
submitMSG(true, “Message Submitted!”)[/php]

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()

[php]function formError(){
$("#contactForm").removeClass().addClass(‘shake animated’).one(‘webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend’, function(){
$(this).removeClass();
});
}[/php]

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:

1
2
formError();
submitMSG(false, “Did you fill in the form properly?”);
Now when we submit an empty form it will shake to let the user know something has gone wrong.

Advertisement
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.

[php]<?php
$errorMSG = “”;

// NAME
if (empty($_POST[“name”])) {
$errorMSG = "Name is required ";
} else {
$name = $_POST[“name”];
}

// EMAIL
if (empty($_POST[“email”])) {
$errorMSG .= "Email is required ";
} else {
$email = $_POST[“email”];
}

// MESSAGE
if (empty($_POST[“message”])) {
$errorMSG .= "Message is required ";
} else {
$message = $_POST[“message”];
}

?>[/php]
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.

[php]<?php
// redirect to success page
if ($success && $errorMSG == “”){
echo “success”;
}else{
if($errorMSG == “”){
echo “Something went wrong :(”;
} else {
echo $errorMSG;
}
}

?>[/php]

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:

[php]$.ajax({
type: “POST”,
url: “php/form-process.php”,
data: “name=” + name + “&email=” + email + “&message=” + message,
success : function(text){
if (text == “success”){
formSuccess();
} else {
formError();
submitMSG(false,text);
}
}
});[/php]

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!


#2

I just added php tags to the code in order to look pretty and easier to read. :wink:
[size=8pt](I like the php tags the best it makes the code stand out better in my opinion)[/size]