WpCanyon

Create an AMAZING contact form with no ready made plugins.

cf_3
Every website should have a contact form. In this tutorial we will make a contact form that will make your visitors say WOW. It will be a cool looking contact form with nice and smooth validation, processed with AJAX.


Demo Source

Here’s what we’re making here :)

validation

fail

success

We are going to have 2 files, the first one is contact.html and the second one is send_email.php.

HTML(contact.html)

<div id='contact_form_holder'>
<form action='index.php' method='post' id='contact_form'>
<h2><img id='contact_logo' src='images/mail.png' /> Contact Us</h2>

<p>
Your Name:
<div id='name_error' class='error'><img src='images/error.png'> I don't talk to strangers.</div>
<div><input type='text' name='name' id='name'></div>
</p>

<p>
Your Email:
<div id='email_error' class='error'><img src='images/error.png'> You don't want me to answer?</div>
<div><input type='text' name='email' id='email'>
</p>

<p>
The Subject:
<div id='subject_error' class='error'><img src='images/error.png'> What is the purpose of the contact?</div>
<div><input type='text' name='subject' id='subject'></div>
</p>

<p>
The Message:
<div id='message_error' class='error'><img src='images/error.png'> Forgot why you came here?</div>
<div><textarea name='message' id='message'></textarea></div>
</p>

<div id='mail_success' class='success'><img src='images/success.png'> Thank you. The mailman is on his way.</div>
<div id='mail_fail' class='error'><img src='images/error.png'> Sorry, don't know what happened. Try later.</div>
<p id='cf_submit_p'>
<input type='submit' id='send_message' value='Send The Message'>
</p>

</form>
</div>

As you can see the contact form sections are splitted with paragraphs. Inside every paragraph there is description text, error div, and the div with the input.

Now, the CSS…

CSS(contact.html)

#contact_form_holder {
    font-family: 'Verdana'; /* this is a nice font-family, at least i think, if you don't like it change it :) */
    font-variant: small-caps; /* making the small letter looks like capital but keeping the size of it to smaller, looks cool */
    width:400px; /* setting a fixed width of the contact form holder will make things easier later (like aligning and such) */
}
#contact_form_holder input, #contact_form_holder textarea {
    width:100%; /* make all the inputs and the textarea same size (100% of the div they are into) */
    font-family: inherit ; /* we must set this, so it inherits the font-family */
    padding:5px; /* and make a custom padding, you can set whatever you like */
}
#contact_form_holder textarea {
    height:100px; /* i never liked small textareas, so make it 100px in height */
}
#send_message {
    width:200px !important; /* the width of the submit button  */
    font-variant: small-caps; /* nicer font-variant (like explained before) */
    border:1px solid black; /* remove the default border and put a normal black one */
    cursor:pointer;
    cursor:hand;
}
#cf_submit_p { text-align:right; } /* show the submit button aligned with the right side */

/* styling */

.error {
    display: none; /* hide the errors */
    /* add some styling */
    padding:10px;
    color: #D8000C;
    font-size:12px;
    background-color: #FFBABA;
}
.success {
    display: none; /* hide the sucess div */
    /* add some styling */
    padding:10px;
    color: #044406;
    font-size:12px;
    background-color: #B7FBB9;
}

#contact_logo { vertical-align: middle; }
.error img { vertical-align:top; }

And now we got this nice contact form.

cf_2

Let’s JQuerify this contact form :)

JQuery(contact.html)

    $(document).ready(function(){
        $('#send_message').click(function(e){

            //stop the form from being submitted
            e.preventDefault();

            /* declare the variables, var error is the variable that we use on the end
            to determine if there was an error or not */
            var error = false;
            var name = $('#name').val();
            var email = $('#email').val();
            var subject = $('#subject').val();
            var message = $('#message').val();

            /* in the next section we do the checking by using VARIABLE.length
            where VARIABLE is the variable we are checking (like name, email),
            length is a javascript function to get the number of characters.
            And as you can see if the num of characters is 0 we set the error
            variable to true and show the name_error div with the fadeIn effect.
            if it's not 0 then we fadeOut the div( that's if the div is shown and
            the error is fixed it fadesOut. 

            The only difference from these checks is the email checking, we have
            email.indexOf('@') which checks if there is @ in the email input field.
            This javascript function will return -1 if no occurence have been found.*/
            if(name.length == 0){
                var error = true;
                $('#name_error').fadeIn(500);
            }else{
                $('#name_error').fadeOut(500);
            }
            if(email.length == 0 || email.indexOf('@') == '-1'){
                var error = true;
                $('#email_error').fadeIn(500);
            }else{
                $('#email_error').fadeOut(500);
            }
            if(subject.length == 0){
                var error = true;
                $('#subject_error').fadeIn(500);
            }else{
                $('#subject_error').fadeOut(500);
            }
            if(message.length == 0){
                var error = true;
                $('#message_error').fadeIn(500);
            }else{
                $('#message_error').fadeOut(500);
            }

            //now when the validation is done we check if the error variable is false (no errors)
            if(error == false){
                //disable the submit button to avoid spamming
                //and change the button text to Sending...
                $('#send_message').attr({'disabled' : 'true', 'value' : 'Sending...' });

                /* using the jquery's post(ajax) function and a lifesaver
                function serialize() which gets all the data from the form
                we submit it to send_email.php */
                $.post("send_email.php", $("#contact_form").serialize(),function(result){
                    //and after the ajax request ends we check the text returned
                    if(result == 'sent'){
                        //if the mail is sent remove the submit paragraph
                         $('#cf_submit_p').remove();
                        //and show the mail success div with fadeIn
                        $('#mail_success').fadeIn(500);
                    }else{
                        //show the mail failed div
                        $('#mail_fail').fadeIn(500);
                        //reenable the submit button by removing attribute disabled and change the text back to Send The Message
                        $('#send_message').removeAttr('disabled').attr('value', 'Send The Message');
                    }
                });
            }
        });
    });

Now we just need to make a simple php file that will process the email and tell JQuery if it succeded in that.

PHP(send_email.php)

    //we need to get our variables first

    $email_to =   'skustrimovic@gmail.com'; //the address to which the email will be sent
    $name     =   $_POST['name'];
    $email    =   $_POST['email'];
    $subject  =   $_POST['subject'];
    $message  =   $_POST['message'];

    /*the $header variable is for the additional headers in the mail function,
     we are asigning 2 values, first one is FROM and the second one is REPLY-TO.
     That way when we want to reply the email gmail(or yahoo or hotmail...) will know
     who are we replying to. */
    $headers  = "From: $email\r\n";
    $headers .= "Reply-To: $email\r\n";

    if(mail($email_to, $subject, $message, $headers)){
        echo 'sent'; // we are sending this text to the ajax request telling it that the mail is sent..
    }else{
        echo 'failed';// ... or this one to tell it that it wasn't sent
    }

Final words

That’s it, hope you like it, i know i do.

If you like it, visit our sponsors, they are located on top right of the page, or SHARE :).
Support this tutorial on DZone

Are you a WordPress developer? Then by all means check my other blog WpCanyon for daily WordPress development articles.

Liked the article?

If you liked the article you can help us out by upvoting or tweeting the article. That would be great. Thanks.

52 Responses

  1. Masoud

    Aug 22nd, 09

    very nice ;)

  2. Boba

    Aug 22nd, 09

    Thanks :)

  3. CertPal

    Aug 24th, 09

    Nice ! The email validation seems a little patchy though. It validated a@ as a valid email address.

    The fade in, fade out adds a nice touch to it.

  4. Boba

    Aug 24th, 09

    Thanks.

    Yea, i know, didn’t want to go to much complex with the validation, will make a separate tutorial for javascript form validation.

  5. Gargo Fanbo

    Aug 25th, 09

    This is a BAD tutorial – you know why? because you think validation is a second class citizen in your programming world – that is the reason, why hundreds of php cms systems have still very stupid security flaws today – because authors like you teach poeple the wrong things. dont get me wrong – your skills are very good, idea and grafix very nice. but you must put validation and security on your agenda.

  6. Boba

    Aug 25th, 09

    Thanks for the comment Gargo. Let me explain…

    This is a comment form, not signup or register for example.

    1) The purpose of this validation is to inform the one that’s contacting that something is not entered correctly and not to stop someone to submit it wrongly by any means necessary.

    2) I didn’t make this form to teach people how to secure their web apps, i made it to show how to make a nice contact form, that’s all.

    3) If i make every tutorial cover everything, from security to design, what do you think how much times in every tutorial will i talk about the SAME THING. That’s why “authors like me” do that.

    4) I bet that all of the readers have read many many tutorials about security, why would i bother then with another one when they just came to see how to make a nice contact form?

    Thanks for the comment, i appreciate it. I’m open to suggestions, so if people want me to talk about the security in every tutorial, i will (just copy paste the explanation, because it’s mostly the same thing)

    Thanks again :)

  7. Jason

    Sep 11th, 09

    I have a few questions if you don’t mind.
    I’m not exactly sure what to do with the CSS(contact.html) and JQuery(contact.html) fields.
    I copied the HTML field into notepad, saved it as an .html file, but I don’t understand what to do with the other two fields.
    I also created the .php file, but I can’t be certain I did it right until I understand the rest.

    Do I need to create a .css file? it would seem logical.
    As for JQuery, I have never worked with that code or any of those files.

    Another question, How am I supposed to get the .png files into my /images folder?
    I don’t see any downloadable material here.

  8. Boba

    Sep 12th, 09

    @Jason – Hi, you can download the source file and check it out there to understand which part goes where.

    You can create a special .css file, but in this tutorial i implemented the css inside the html.

    The downloadable material is in the source. The link is bellow the description on top of the tutorial.

  9. Jason

    Oct 5th, 09

    Hi i like the Form. But can u please write the details in Steps to put this on a website. I tried to understand the part of the contact form, but the JQuery?
    I made a html file contact, i have changed the php info of the sendmail to my email adres. But it does not work. where do i put the JQuery?

  10. Boba

    Oct 5th, 09

    In the html page.
    <script type=’text/javascript’>

    THE jQuery CODING HERE

    </script>

  11. Drew

    Oct 26th, 09

    Hi, Great tool!
    One question: can I test & send email from my computer using localhost? Any tips? Thanks

  12. Boba

    Oct 26th, 09

    Sure, you just need to make few updates on the localhost server settings.

    You might want to check this out:
    Sending e-mail from localhost in PHP in Windows Environment

  13. vicky

    Nov 4th, 09

    iam trying to make this form for my site , but after uploading both php and html file iam getting a blank page http://angelcomputers.co.in/Complaint.html please helpppppppppp

  14. Boba

    Nov 4th, 09

    @vicky – http://tutsvalley.com/files/contactform.rar Download the source files from there, so you just need to change the email and upload the files.

  15. Eli

    Nov 24th, 09

    first of all, great tutorial/form!

    I am trying to implement this into my contact form.. basically just using your structure with my stylings but I can’t seem to get the email to send. I the error message everytime. I tried downloading your source files but my computer can’t read them.. do you have it in a zip file? I also tried copying your demo page and using that with my edited send_email.php page.. still didn’t work.

    any ideas?

    http://nvmber9.com/contact

    thanks in advance :)

  16. Boba

    Nov 24th, 09

    Sent you an email… :)

  17. crazedtraveller

    Nov 26th, 09

    I’ve added the contact form (with a few tweaks) to my site. The form seems to work but it won’t send? the send_mail.php is in the root – help!?

  18. Boba

    Nov 26th, 09

    @crazedtraveller – You removed the subject field in the html but didn’t remove it from the javascript(jquery). Remove these lines:

    var subject = $(‘#subject’).val();

    if(subject.length == 0){
    var error = true;
    $(‘#subject_error’).fadeIn(500);
    }else{
    $(‘#subject_error’).fadeOut(500);
    }

    It should work after you remove those.

  19. crazedtraveller

    Nov 26th, 09

    thanks for your quick reply – removed the code and the form appears to work in terms of the pink/red writing coming up etc, but still it won’t send….should the page be .php or .html ok? i’ve tried both…

  20. robert

    Nov 29th, 09

    Hi,
    Thank you so much for this tutorial

    I just have one question, when using this is it possible to track maybe the IP address of the computer that submitted the message??

    Thanks,
    Robert

  21. Boba

    Nov 29th, 09

    Glad you like it :)

    You can get the ip address by using $_SERVER["REMOTE_ADDR"] in php.

  22. Miguel

    Dec 2nd, 09

    Wow! nice one… very good tutorial..

  23. Eli

    Dec 12th, 09

    Hello again,

    I am using this form/script again, but this time I am adding two file submission input fields. These aren’t required fields so they don’t need to pass the ‘length’ test, but in the email i get doesn’t post the emails. I am using:

    $photo1 = $_POST['photo1'];
    $photo2 = $_POST['photo2'];

    Any thoughts?

    Thanks,
    Eli

  24. Eli

    Dec 12th, 09

    oops.. what I meant to say was that the email i get from the submission doesn’t post the photos. only a blank.

  25. Max

    Dec 13th, 09

    thank you for this tutorial! little bug: line 129 is missing a “</div>”

    best, max

  26. Boba

    Dec 13th, 09

    @Eli – You can’t attach files like that. It’s a bit harder. :)

    @Max – Thanks for pointing out, fixed :)

  27. stosh

    Dec 15th, 09

    Great tutorial. Thanks for putting this together.

    I am trying to implement this in my site (not quite live yet). I changed the email address, but I don’t ever receive a message. Email me and I can give you the URL of my test area to check out.

    Thanks for the help.

  28. JohnnyBrave

    Dec 17th, 09

    Hi Boba

    Nice tutorial on the GUI for an input form. I am a C++ programmer with asp, php, perl and css among my other web scripting languages. I agree with you in regards to security. It is a pity others cannot see the logic between a GUI and a security OOP. Dont listen to those who bash on about security… it seems they wanted you to go the whole nine yards forgetting that you’re putting in your time and effort for FREE!

    PHP is quite a good server side scripting for formatting and catching errors on integers, charactors and symbols. So if they need security pointers on how to catch and format errors to validate fields then they are indeed reading the wrong tutorial lol.

    Thanks for your effort. I am more of a programmer than a designer so tutorials like these assist me in ways I can implement both design/interface with coding.

    10/10 :)

  29. Boba

    Dec 17th, 09

    @stosh – Do you get the “mailman is on his way” message :)

    @JohnyBrave – Thanks :)

  30. JohnnyBrave

    Dec 17th, 09

    @Boba – No prob. Incidentally I prefer PHP to do detailed secirity checks on the server side of form fields and use Javascript to do the client side checks.

    Bit of an overkill but it works for me. I haven’t located where to download the demo or source files for this tutorial but looking at the example I know exactly what to do anyway lol

  31. Boba

    Dec 17th, 09

    On the top of the article right after the thumbnail and description you will see “Demo Source” in black color :) but those are links. Newer tutorials have styling for those links but i didn’t get the chance to implement it on older tutorials yet. :)

  32. JohnnyBrave

    Dec 17th, 09

    OK I will rar it…
    Thanks

  33. stosh

    Dec 18th, 09

    I do get the right message, but it doesn’t come through to my account. It is a google apps hosted domain email address.

  34. Boba

    Dec 18th, 09

    Well the problem isn’t in the coding then. Check the SPAM maybe it stored it there.

  35. Rayhan

    Dec 23rd, 09

    Hello TV,
    This is great, but can we combine ; integrated Ajax Fancy Captcha to this nice contact login form?

    Thanks

  36. Peter

    Dec 25th, 09

    Hi! My problem is that is there any index.php somwhere? In contact.php there is raw: and after i press submit message it says cant find file.

  37. Boba

    Dec 25th, 09

    @Rayhan – Maybe… :)

    @Peter – There is no index.php, you open the contact form using the contact.html page. I’m assuming you get the error from firebug, right? There is an php file (send_email.php), do you have it?

  38. Peter

    Dec 26th, 09

    Sorry for my english. I have the sen_email.php file. I’m not a great programmer :), I put this nice contact form under AppServ or XAMPP and it works ok. But if I put it on a web server, after pushing the send message button it says the page (index.php) not found on this server.
    I’am not really understand why.

  39. Peter

    Dec 26th, 09

    Oh, the problem was that I call the form through ajax (html in div) :)

  40. Zaman-A-Piri Pasa

    Dec 28th, 09

    Thanks for sharing a nice tutorial.

  41. WEbKILLER

    Jan 12th, 10

    Hi everyone!!

    This is really an amazing contact form!! thanks to BOBA !!!
    Just a small addition I’ll do is the e-mail validation:

    add this in the jQuery code after the declaration of the variables:

    var re = new RegExp(/^[a-z0-9_\-]+(\.[_a-z0-9\-]+)*@([_a-z0-9\-]+\.)+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel)$/);

    and then on the email check we’ll do it like this, instead of:

    if(email.length == 0 || email.indexOf(‘@’) == ‘-1′) {
    var error = true;
    $(‘#email_error’).fadeIn(500);
    } else {
    $(‘#email_error’).fadeOut(500);
    }

    just put this:

    if(email.lenght == 0 || !email.match(re)) {
    var error = true;
    $(‘#email_error’).fadeIn(500);
    } else {
    $(‘#email_error’).fadeOut(500);
    }

    I wish it could help some of the crazy “security” people!! :D:D:D
    just joking!!

    see ya

  42. Mike R

    Jan 23rd, 10

    Very nice! This is exactly what I was looking for!

    I’m having some issues, though. I added the form to my site and it appears to work fine but I do not get any mail. I changed the email in the php script. Am I supposed to change the form action=”index.php” part in the html doc?

  43. Boba

    Jan 23rd, 10

    @Mike – Give me the link to the page where you installed it and i’ll check it out.

  44. Andrew

    Jan 24th, 10

    That is exactly what I’m looking for. However, there was this error though…

    I cannot get the email send. Only stop at “Sending…” and it doesn’t go anywhere. The form can check validation and all, just don’t send :?

  45. Boba

    Jan 24th, 10

    @Andrew – Can you give me the url to the page where you have it set up and will see what i can do :)

  46. Andrew

    Jan 24th, 10

    @Boba, check http://zhngdesign.com/zhngdesign... Thanks a lot!

  47. Boba

    Jan 24th, 10

    You got an “500 internal server error” on the php file that sends the email ( http://zhngdesign.com/zhngdesign/send_email.php )

    http://www.checkupdown.com/status/E500.html

    Find the error log somewhere on your server and you will find the issue.

  48. Andrew

    Jan 24th, 10

    @Boba, thanks a lot! Will check into it…

  49. Stacey

    Jan 29th, 10

    Hi, I tried uploading this to my website as I want to have a contact form on there and it all looks fine except I get this error message:

    The requested URL /contactform/index.php was not found on this server.

    Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

    I haven’t put it on a page of my site yet, I just have what was included in the download.. but I’d like to know how to get it to work first. I’m new to php, so I don’t understand what this means exactly and would appreciate some help :)

    Thanks!

  50. Boba

    Jan 29th, 10

    @Stacey – Did you download the source files or you copy pasted the codes from this page?

    Edit:

    Sorry i just realized you said you downloaded the files. Can you give me the url to where you uploaded it.

Leave a Reply

Trackbacks and Pingbacks

  1. Twitter Trackbacks for Create an AMAZING contact form with no ready made plugins. « TutsValley [tutsvalley.com] on Topsy.com
  2. jQuery AJAX og annet.. « PHP på Norsk!