How to make a contact form with Bootstrap 3 ? (JQuery/PHP/HTML5/JqBootstrapValidation)

Hey guys!

Today we will talk about such essential feature for any website as contact form. Recently, while working on one of the projects, I had a pleasure combining couple of very nice tools (Bootstrap 3 + JQuery + jqBootstrapValidation), which resulted in minimalistic , but powerful contact form, that would be a good addition to any website.

Contact me form

VIEW DEMO          CODE

In this post I will walk you through the process of developing this form. Also if you just want to put it in your website, just pulled from my github repo and have fun.

Sounds good ?

Let’s start.

Also, if after reading this post you feel that you need help to set it up or configure it for yours needs:

let me help you

When I was developing my form I had in mind following goals:

– Minimalistic design
– Track person’s contacts for future communication
– Send form information directly to my email
– Validate input – client side and server side
– Show success when form is sent, or provide alternative method if something went wrong

As you might see – nothing special. I would love if somebody else would provide me this solution yesterday, when I was working on my project – this could save me some time! :)

Let’s divide our workflow into sections:
– Required Libraries
– UI
– Client-side Validation, JQuery – PHP Interaction
– PHP (so called server side)

Required Libraries

We will require following libraries :
Botostrap 3
–  jqBootstrapValidation

So all you need to do is just download necessary files and put them in.

After getting Bootstrap and jqBootstrapValidation our website tree will look like this:


– –  css
– – – bootstrap.min.css
– – js
– – – bootstrap.min.js
– – – jqBootstrapValidation.js

Let’s move to the UI part.

UI

For the UI we will use Bootstrap 3 and some attributes from jqBootstrapValidation.js . I won’t cover Bootstrap 3 components as it will take far too long, but if something is unclear, please shoot me an email and I will clarify that for you.

So in the root of our website we need to create file form.html .

Final version of /form.html will look like this:

Sorry for this formatting, it’s hard to put code into WP, please find formatted version of form.html here

If you are familiar with Bootstrap – this code is pretty straightforward.

There are couple of important things I would like to point out:

  1. Since we are using jqBootstrapValidation, we need to put novalidate attribute into our form tag, otherwise HTML5 validation will clip jqBootstrapValidation validation.
  2. To change color/style of your error messages just change “.help-block” CSS class
  3. data-validation-* classes are used to specify custom message when user does something incorrectly. You can find more about those here.
  4. jqBootstrapValidation library looks at input and textarea tags and automatically puts validation if needed. For example if there is a “required” attribute, it automatically will put error message if the field is empty.

That’s all I can think of, if you have additional questions, please send me an email, or ask me in the comments below the post.

Client-side Validation, JQuery – PHP Interaction

So now we have finished the design of our form. Next step is to activate jqBootstrapValidation library, pass users data to PHP, which will send an email and finally show something to the user.

Most of these is done in one tiny JQuery function.

Here it is (file js/contact_me.js):

For the most part I have took the function from jqBootstrapValidation examples. However, there are couple of things particularly interesting to us.

jqBootstrapValidation allows to overwrite submit on success behaviour, which I am doing in this case. If user submits everything without errors – I do a POST request to the file bin/contat_me.php with name, email and message.

File contact_me.php, which we will code in the next section, sends me an email with everything that user filled in. Also, I check If I am able to connect to this file, in this case I send back “Message sent successfully” to the user, otherwise I give an error telling user to email me directly ( use cases: for example if mail server is down, if validation on server side failed, if permissions to php file are incorrect etc) .

There is not much to add, but if you have any questions regarding this function do not hesitate to ask.

PHP (so called server side)

Finally, we got to the last piece of this puzzle. I have a php file that does some validation on the data received from form and sends me an email.

Here is my PHP file ( bin/contact_me.php )

As you might see my PHP file is even more simple. Of course you can add extra validation on top of it. For my use case I am just checking if fields are not empty and if email has correct format. If everything is correct, I create an email and use PHP’s mail function to email it.

That’s it.

You can find all these files here.

I hope this function will be useful for you!

Regards,

Anatoly

Update:

F.A.Q

(Thanks a lot to Corey Russell  for resolving some of the occurring issues)

Q:  I see “Sorry <Name> it seems that my mail server is not responding… Could you please email me directly to….”

A:  1. Go to line 26 of the contact_me.js file you have. There you’ll see the url for contact_me.php. Make sure that url is correct. I think by default it is pointing to a folder called bin.
2. If you try it from your desktop it won’t work as it doesn’t have a php server/client installed.

 

About the author

Anatoly Spektor

IT Consultant with 6 years experience in Software Development and IT Leadership. Participated in such projects as Eclipse IDE, Big Blue Button, Toronto 2015 Panam Games.

View all posts

146 Comments

      • Hello Anatoly,
        Thanks for this wonderful tutorial. I am a new web developper. I am trying to run this example on my Desktop but it’s not working. I have got XAMP server installed ùn my pc ! I am getting this error ” it seems that my mail server is not responding… Could you please email me directly to….”” Can u please help. Thanks.

    • Hey Thomas,

      I don’t know if you’ve fixed it yet, but I had a problem with the mail server as well. I fixed the issue by making sure the correct path was entered on line 26 of the contact_me.js file. Hope this helps if you haven’t got it already.

      Corey

  • Hi!
    I have this problem
    “Sorry Tiago it seems that my mail server is not responding… Could you please email me directly to….”
    How can fix this? I have not much idea of php

    Thanks for all!

    • Tiago, go to line 26 of the contact_me.js file you have. There you’ll see the url for contact_me.php. Make sure that url is correct. I think by default it is pointing to a folder called bin.

      You can see that I have a working example on my site. http://www.coreymrussell.com. Click the contact link and you can see that it works.

      • Great work.

        in the text area “Message”, the placeholder is not shown, all i can see are empty spaces.
        in the demo link, it is OK – there is no problem.
        But when i looked in coreyrussell website, i see the problem i mentioned above.
        could you please check coreyrussell site, and tell me how to fix it.

        Thanks,
        Shay

  • Shay,

    I hadn’t actually noticed that until you pointed it out as I did not wish to use placeholders. I have updated my contact form, however, to show you the only viable solution I could find. It seems as though placeholder isn’t playing nice with textarea in bootstrap 3… so I just put the text I wanted between the tags.

    ex:

    Your Message Here

    Thanks,

    Corey

  • Corey,
    Have a long form that I am using your tutorial with. The only issue I am having is posting any checkbox from the form.

    Here is the input:

    Select: Dear Tastebuds: You’re Welcome.

    Here is what I have in the JS file:
    var library_selection = $(“input#library_selection”).val();

    data: { library_selection: library_selection}

    and the PHP Post:
    if(!empty($_POST[‘library_selection’])) {
    foreach($_POST[‘library_selection’] as $check) {
    echo $check;
    }
    }

    Email Body:
    $email_body = “Libary Selection: $check n”.

    Any thoughts would be great!

    • Okay here is the input again without the brackets:
      input type=”checkbox” value=”OD_Dear_Tastebuds” name=”library_selection[]”

    • Eric,

      This is not my script. I just had some of the same issues that others were having, and was happy to help. As for your issue set the name in the form to check_list[] and you will be able to access all the checkboxes as an array($_POST[‘check_list’][]).

      Let me know how this works for you, or if something else solves your problem.

      Thanks,

      Corey

      • the php looks like:

        if(!empty($_POST[‘check_list’])) {
        foreach($_POST[‘check_list’] as $check) {
        echo $check; //echoes the value set in the HTML form for each checked checkbox.
        //so, if I were to check 1, 3, and 5 it would echo value 1, value 3, value 5.
        //in your case, it would echo whatever $row[‘Report ID’] is equivalent to.
        }
        }

    • Eric,

      This is not my script. I just had some of the same issues that others were having, and was happy to help. As for your issue set the name in the form to check_list[] and you will be able to access all the checkboxes as an array($_POST[‘check_list’][]).

      Let me know how this works for you, or if something else solves your problem.

      Thanks,

      Corey

      • Thanks for the reply! Not sure why I am having so much problems with this.
        Does the jQuery need to be changed at all? I have a Terms & Conditions checkbox that wasn’t working but now is. var terms_and_conditions = $(“input:checked”).val();
        For the check_list its still posting nothing. Changed the name to check_list[], my php is:
        if(!empty($_POST[‘check_list’])) {
        foreach($_POST[‘check_list’] as $check) {
        echo $check;
        }
        }
        and jQuery: var check_list = $(“input#check_list”).val();
        Form submits but the check_list post is blank.

      • HA! Man I just realized what “This is not my script.” reply was all about. Thanks for reply! Will let you know how it goes.

  • Hi Corey i have this problem :
    “Sorry Marco it seems that my mail server is not responding… Could you please email me directly to….”

    I copied the URL from your personal site like :

    $.ajax({
    url: “contact_me.php”,

    without folder and it doesn’t work.

    this is the site : http://www.zippashirt.it

    Can you please help me

    • I tired it from your site and it is working. If you try it from your desktop it won’t work as it doesn’t have a php server/client installed. But it seems to be working for me on zippashirt.it

    • Luis,

      1. Make sure you are testing it from your web server. Do not test it from your desktop as it will not work.

      2. As mentioned in previous comments, go to line 26 of the contact_me.js file you have. There you’ll see the url for contact_me.php. Make sure that url is correct. I think by default it is pointing to a folder called bin.

      Thanks,

      Corey

  • Hi Anatoly,

    Many thanks for the form. I have installed it and have it working. However I would like to be able to send two messages to two different email addresses when the form is submitted.

    Would I be able to add this to the contact_me.php file and where you create the email body I would create two sections of code, one for $to1 and $to2, $email_subject1 and $email_subject2?

    Any help gratefully received.

    • Ok Nic. Try using an array and implode it to a comma separated string.

      $recipients = array(
      “youremailaddress@yourdomain.com”,
      “yoursecondemail@yourdomain.com”
      );
      $email_to = implode(‘,’, $recipients); // your email address
      $email_subject = “Contact Form Message”; // email subject line

  • I put the php file on the site root folder and playing on the MAMP server on my desktop.
    ” Your message has been sent. ” That is great!
    However, when I checked my email, I do not get the message to my email either.
    Could you help me out?

      • I am using 5.3.6 version of php. I have been digging for the answer to this question and found out it might be the problem of MAMP having no mail server. I believe you are right. I didn’t launch my website to a web server yet and I will try to figure it out then. Thank you for your quick reply. ^^ BTW: Do you have recommended web server?

  • Hi, Thanks for the tutorial. Great work!

    Im running it from a web server (@godaddy) but I don’t get the message “Your message has been sent”.

    What could be the problem?

    My php skills are very very basic.

    Thanks

  • Most excellent! It’s working fine here!

    One question:

    How to redirect the user to a different page after the form is successfully submitted?

  • Hi all,

    What and where do I need to change to adapt this to a different framework from Bootstrap (Using Gumby)?

    Appreciate any help that I can get!

  • hi, thx for this beatiful bootstrap form,
    i have problem with this so, it send mail with chrome but most of time doesnt send mail in IE and in Firefox i dont know why, pleay help

    thx.

    • Hey Mike,

      Since mail is sent “server-side” through php script , I don’t think that mailing action is browser-dependant, unless you have some plugin in one of the browser that actually sends an email.

  • Hey,
    thanks so much for the form!

    I wondering if you could help me with a problem:
    I’d like to add two more fields: Business name and phone. I put the input box, but without the right code it doesn’t send it to my email. Could you help me out?

    Thanks,
    Nate

    • Hey Nate,

      I am glad that you like the form. It is great that you are adding fields! Adding fields is not hard at all. I don’t want to give away the whole solution, but I am glad to give you couple of tips. Trust me adding fields is super easy!

      Here is where you should look at:

      1. Add input text boxes for you fields to the UI the way I am doing it lines 14-16 of form.html
      2. add your fields to client side validation (js/contact_me.js) the same way I do it in lines 17-18 of contact_me.js

      3. In PHP catch client input like I do it in lines 12-13 and add variables where save client input into mail function (line 24) all this inside contact_me.php

      Try it and tell me how it goes :)

      Regards,

      Anatoly

  • I want to ask one question that how the submit button is associated with the javascript file which calls to the server side code in your code in “js/contact_me.js” .Actually i need to send some data to the database from html page i want to use your code to call server side code.

  • Excellent article, many thanks.
    Just wondered if anyone is aware of any way to hack the validate script so that errors are displayed in bootstrap popovers instead of help-blocks. Due to cross domain issues, I have to iframe this form into a modal and the extra space to accommodate the help-blocks is damn ugly.

    I realise this is not your script but just checking as I can’t find anything online.

    Cheers,
    Turbs

  • First off, awesome work!
    This would be really helpful.
    However, its saying “Mail Sent, but I don’t get any emails at all.
    PLEASE HELP!

    • I don’t believe in captchas they are making easy-enough process so much difficult, especially ones that hard to read :) But In case you need one, there are plenty of easy to use add ons that you just copy-paste and you have a captcha :)

  • Hi, I have a little problem, when I send a message (I put mi email on line 17 y 22 contact_me.php), I recive two messages, and It is a bit annoying. Any solution? :)

  • Hi, everything is working with the form. Thanks for your work.
    Only one thing I need to do to finish the form and I have have tried everything I know. And I am not say that I know a lot, just enough to get the though. So I would appreciate your help.
    In my form I have a checkbox to check if someone would like to subscribe to a newsletter:

    Newsletter

    I would like to receive your e-newsletter.

    I do not know what alterations are needed to contact_me.js to POST the value to contact_me.php
    If you could help it would be much appreciated. Thankyou.

  • Tried to put in the checkbox code but it didn’t accept it.
    <!—->
    <!–Newsletter–>
    <!—->
    <!—->

    <!—->
    <!—->
    <!—->

  • Hi Anatoly,

    Thanks for the contact form, it works like a charm! I had it up and running in 35 mins. As you mentioned, I had to change the name of the .php file, but that’s it.

    Sincerely,
    Stephan

  • Hi Anatoly,

    First off great form, it works really well and it’s great having the fall-back in case the mail server is unavailable.

    I’m currently trying to extend the form and add a select dropdown but am having trouble getting the value passed through to the contact form. I had a look over the comments here and saw one from Nate which was along similar lines.

    The dropdown is displaying on the form fine, I have updated the contact_me.php to collect the new post variable (called location) and have updated the contact_me.js to add the new variable after line 19.

    Using chrome debugging on contact_me.js and some breakpoints I can see name, email and message getting set but the new location variable remains undefined.

    I have added the following code:

    // form.html – added within form

    NoLocation
    Location1
    Location2

    // contact_me.js – added after line 19
    var area = $(“input#location”).val();

    //contact_me.php – added after line 14
    $location = $_POST[‘location’];

    I’m really not sure what the issue is – although I’m thinking I’ve missed or messed up something in the contact_me.js.

    Any pointers would be most welcome!

    • Seth, had the same problem yesterday with a select.
      The problem is use “input#location” in the var area assignment.
      Use only: var area = $(“#location”).val();
      I waste much time in this problem so i put the solution here!

  • Thanks for your tutorial. When I follow the tutorial first, I have no problem querying my message to my database. But when I change the form.html to form.php it doesn’t work. It doesn’t even calls the action from ./bin/contact_me.php. what happened?

  • See if the tires are flat and wide, whicch
    makes it harder for you to go for this ever since this time last year.

    Ardent bikers mayy bring their riding own bikes. The cyclist increases the distance for the same period.
    Try to better your time each time you go for a race licence.

  • Hi,

    thanks for this useful form 😉

    It seems that everything is working fine for me… I even have the “message successfully sent” message… BUt I never receive any mail :'(

    I have correctly setup my email in the contact_me.php file on line 17 (and 22)

    do you have any clue what could cause this?

    you can check the form on the site http://lecosiweb.free.fr/#contact

    thanks for your help

    • This has to do with your mail server. Make sure you have your mail server set up properly. You could also try programs such as FakeSMPT that act as Fake Mail Sever, in order to see if email are coming through. If they are, you will need to set a real mail server.

      • Hi,

        thanks for your answer.

        I replaced the form by a h ref to a php file with the mail function hard coded (
        mail(mail@eurfref.fr,”text”,”text”)

        and it’s working fine… ;s

        meaning the issue is not from the mail server nor the PHP mail function not working.

        If you have any way of opening a window with the variables listed I could try to debbug this 😉

        thanks again

    • Hi,

      I managed to have it working. I don’t know why but it seems that all the pre-check seems to be the issue…

      I commented all that part:
      // check if fields passed are empty
      //if(empty($_POST[‘name’]) ||
      // empty($_POST[’email’]) ||
      // empty($_POST[‘message’]) ||
      // !filter_var($_POST[’email’],FILTER_VALIDATE_EMAIL))
      // {
      // echo “No arguments Provided!”;
      // return false;
      // }

      and now everything works fine

  • Can anyone help me with this ? what does the control-group and controls classes do and have checked the bootstrap and bootstrap validation documents and can find nothing on them.

    Thank you

  • Thank you for this great and simple contact form! i have one question: how to prevent double submit?
    My server takes about 10-15 seconds to send the message (dunno why), while that is happening you see nothing and probable people will submit several times…
    I’m not much of a coder or a programmer, i tried several solutions i found on google but nothing seems to work for me…

    any ideas?
    thank you

    • Sorry for the double post… i finally disabled the submit button after clicking it, but i have another question:

      How can we enable a “sending, please wait” alert, after clicking the submit button and disappears with the “message sent” alert? takes too long to process and see the “message sent” alert…

      thank you,

  • I used same UI code and same js files. but it give error message “Sorry Rahul it seems that my mail server is not responding… Could you please email me directly to”

  • I am using this code in my html website. I used same UI code and same js files. but it give error message “Sorry Rahul it seems that my mail server is not responding… Could you please email me directly to”
    How to fix it?

  • Hi Anatoly,

    Really nice script! The only thing i am trying to find out is how to push an telephone number trough the digital line….

    In HTML i added:

    In JS I added:
    var telnr = $(“input#telnr-contactformulier”).val();

    But i really dont know any PHP. So how can i load extra lines of information in to the e-mail?
    Do i refer to the code in JS (‘ telnr’) ?

    What does the n means or what does it do?
    $email_subject = …..
    “Email: $email_addressn Message n $message”;

    Thanks in advanced for you’re reply

  • Taking polls and exercises up on everyday base will allow you to
    boost your grammar to a great level. Note the errors down which you create by getting more exercises in that particular notion and improve it upon. Training grammar
    isn’t limited to polls and exercises but
    basically using it inside your everyday lives.

  • Hello, How i can set up this contanct form to answer to the my client e-mail?
    Now when i click “Reply” on gmail its going to reply to “myhostinglogin@MYSERVER.COM.

    In details i have client e-mail, how i can put it to reply input?

  • Hey Anthony,

    Is it possible that the contactform does’ not run without adding “jQuery lib” in the section. Because when i put it in the bottom of my html (for faster loading purposes) it won’t work. Perhaps i am skipping something?

  • Hey Anatoly,
    Thank you very much for this! New to PHP so this is great! I’ve used it on a site for a client and it’s working. However, I’ve tried using the same files to add a registration form to the same site, but on a different page. I’ve changed the file names to register_me.php and register_me.js and have pointed to the register_me.php in the js file but can’t get this new registration form to work.
    I also added some fields and modified the php file to include them <– could that be the issue as to why it's not sending?
    Thanks again!

    • Me either…. I followed seth’s post, but not working. I think there is something on the html /PHP side I’m not listing right. But the form won’t submit after I add a “subject” dropdown field. Figured code would make it easier to debug:

      Please Select 

      Support/Help
      Wholesale
      Other

      PHP Added:
      empty($_POST[‘subject’]) ||

      $subject = $_POST[‘subject’];

      JS Added:
      Tried Both Ways
      var subject = $(“input#subject”).val();
      var subject = $(“#subject”).val();

      Tried Both Ways
      data: {name: name, email: email, message: message},
      data: {name: name, email: email, subject: subject, message: message},

      Final thing, resetting the subject field after submit will be my next question.

      Thanks a ton

  • The big problem I have is the form validation happening as soon as the user starts to type. This is obviously bad user experience especially for the email field. The user is getting an error as soon as they type the first letter. Can anyone tell me how to wait until the user has finished entering the full email address before the validation is performed?

    Paul Yoder has managed it with AngularJS http://blog.yodersolutions.com/bootstrap-form-validation-done-right-in-angularjs/

  • Normally I don’t learn post on blogs, but I would like to say that this write-up very pressured me to check
    out and do so! Your writing style has been surprised me.
    Thanks, very great post.

  • Hi, I want to add one more form to same page with in a modal but I face with a problem that is not working js and .php file I think.

    Can I specify the div that contains form to seperate the js files?

  • Very great post. I just stumbled upon your blog and wanted to say
    that I have truly enjoyed browsing your blog posts.

    After all I’ll be subscribing to your rss feed and I hope you write
    once more very soon!

  • hey. great form. I’m trying to add checkboxes though – and can’t work out how to get them working. Any help greatly appreciated!

  • Thanks for sharing the amazing contact form tutorial. I just need assistant adding selected attribute to php contact form. Any help

  • How would you make an input item optional? I’ve tried everything I can to get the phone item optional, but either it still tries to validate, or it says message successfully sent, but no message is actually sent. works perfectly in it’s original state.

  • Hi there! Loved the contact form, I’ve got it working just fine.
    I’m curious about one thing you might be able to point me in the right direction; what if I need to show the validation messages in other languages? Do you know if there’s a jqboostrapvalidation.js in Spanish, for instance? Changing that will be enough, or should I also need to replace other files?

    Thank you for your time!

  • Hi. It works for me, but I have a another problem. My website has 4 pages (home,about me,gallery and contact). After I installed this form contact in page contact, I can not go back to other pages. Meaning when I am in the page contact.html I can’t access the orher pages or external links. I think that problem is from jquery, but I can’t solved it.
    Can you help me please ?

  • PHP function didn’t return properly errors. This code
    “echo “No arguments Provided!”; return false; ”

    Will show no error on client side, but will show message that email is send. Also not working mail() function (for example: Failed to connect to mailserver) didnt show error.

    It works when everything goes OK but when something goes wrong still shows ’email sent message’. Very confusing.

  • hello buddies
    This
    But how can i use it with an file upload input ?
    How should i modify “contact_me.php”
    I really have no idea

Leave a Reply

Your email address will not be published. Required fields are marked *