enavu webdevmania tutsvalley psdestination
visit the enavu network
86 Comments Article Title Overlay Article Title

Create an AMAZING contact form with no ready made plugins.

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.

DZoneDiggDesign FloatDeliciousBlinklistRedditFacebookGoogle BuzzTwitterStumbleUponTumblrShare

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 =   '[email protected]'; //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.

Related posts:

  1. Create a Disappearing jQuery Dialog Message (Growl Like)
  2. 10 Amazing jQuery Plugins To Improve Your Forms
  3. Web Forms: Semantic Mark Up in our Forms [part 2]
  4. 10 Extremely Useful Wordpress Plugins
  5. Top 10 jQuery Modal Box Plugins

Slobodan Kustrimovic

This author has yet to fill his BIO.

Did you absolutely LOVE this article... share it!

Comments

  • very nice ;)

  • Thanks :)

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

  • Thanks.

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

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

  • 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 :)

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

  • @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.

  • 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?

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

    THE jQuery CODING HERE

    </script>

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

  • 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

  • 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

  • @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.

  • 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 :)

  • Sent you an email… :)

  • 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!?

  • @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.

  • 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…

  • 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

  • Glad you like it :)

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

  • Wow! nice one… very good tutorial..

  • 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

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

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

    best, max

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

    @Max – Thanks for pointing out, fixed :)

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

  • 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 :)

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

    @JohnyBrave – Thanks :)

  • @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

  • 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. :)

  • OK I will rar it…
    Thanks

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

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

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

    Thanks

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

  • @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?

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

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

  • Thanks for sharing a nice tutorial.

  • 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

  • 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?

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

  • 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 :?

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

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

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

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

  • 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!

  • @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.

  • Cool, I finally stumbled to a site about this! I was daydreaming about it this morning (well technically evening dreaming as it was evening time ) and now I discover this site. Coincidence alright. Might be checking back!

  • hello –

    thanks for the code! however, I’m having a hard time getting this to work. in the second line of your contact HTML code, you reference an “index.php” file:

    there wasn’t an “index.php” file in the download. I’m not sure if I’m missing something?

    also, the file in the download was “contact.php” (not “contact.html”) and it seems like an html file.

    I’m somewhat new to the AJAX/php world … any suggestions would be greatly appreciated!

    thanks again!

  • Great contact form but i have one problem.
    When i insert the script the footer of the page goes up and sidebox down…real mess :(

    Can somebody help me out ?
    Thanks

  • very nice tutorial.

    is it possible to fade out the error message of an input-field as soon as someone writes something in this field?

    thanks for help :)

  • Hi! I can’t make it work! Can I send you the files by e-mail as I have no website for now? thanks

  • awesome tutorial!

    im having some trouble getting the demo to work though? uploaded it straight to the server, didnt change anything except the email address destination. any thoughts?

    http://seanehalpin.zxq.net/contact.php

  • This is great! Just what I needed! Only one thing missing for me, and I really don’t know how to fix it… I would like to disable numbers in the name field… How do I do that? (I’m very new at this)

    Thanks again :)

  • Nevermind! I just found the solution and I’m feeling so happy with myself! :D

    Thanks anyway for the great form!!

  • Hey!
    Thank´s for this form! I´m using with diferent style, but with your code…
    I need to know, How can i see the name (variable) who sends the form in my mail box. I only see the mail, and the other variables, but not the “name”
    Thanks a LOT!

  • GREAT TUTORIAL!!!!

    Thanks a bunch! :)

  • Thanks you so much

    I have the same issue

    WHat happened to the Name Varible

    I am trying to adjust code, with no luck

    Did i do something to break it, or did it never work?

  • I concur with Niko…when I receive an email from this form, the “Name” variable is missing.

    Any ideas why it is not being sent to the recipient email? Thank you in advance.

  • …anyone else figure this out yet?

  • is it possible to support other languages and letters for example polish signs? It works fine, sends the email but it displays crap everywhere where polish signs are supposed to be

  • To Danny,
    If you want to receive the name I would suggest you customize it a little bit.
    Make a variable and put the info that you wish inside of it like this:
    //this variable will hold your message
    $content= “From $name ($email) $message”;

    Then alll you have to do is change if statement from:

    if(mail($email_to, $subject, $message, $headers)){

    To:
    if(mail($email_to, $subject, $content, $headers)){

    Hope that helps!

  • Congratulation, nice work ! i enjoy this contact form. it works in local, but i tried to insert this into the index.php of my wordpress blog, (yes, directly on the main page) and the request pending on “send…” and the mail never arrive. I am a newbie with wordpress, maybe wordpress don’t allow other php files exept plugin or something like that, i don’t really no.. Have you a solution in this case?

  • Really a great form…elegant…I’ve added telephone and address fields in form and all validation working including email…but need to get the newly added field data in the email…suggestions?

  • Please disregard prior comment…used a variation of the Alonso to Danny recommendation…any recommendations to add more robust email checking (could not get Webkiller’s to work) and telephone number checking…and to remove html from comment/message…thanks again…great form.

  • Apologies to Webkiller…my error – the email check does work great…do you or Boba or anyone else have something similar for telephone check and to remove html from comments…?

  • HI great work my man. I am desperately in need of help. I just found your tutes here and I must say its helpful but for one thing. I can’t seem to get it to send it keeps telling me about some missing index.php. what do i do?

  • great work, one question, how do i add validation for numbers?

    thanks!

  • #
    # Your Email:
    # You don’t want me to answer?
    #
    #

    You forgot to close the last at the top of the page at HTML(contact.htm)…
    Thanx for the tut it helped me alot meahnn!

  • hi, great form, thanx! i put it into a DIV which slides up and down – wokrs perfectly. one strange thing happens though – whatever i put under the sliding DIV with the contact form gets “taken” by it and in result everything underneath slides up and down with the form. DIVs are closed correctly, must be a conflict between the slide and the form-script… any idea?
    thx. greets from rome!

  • solved my problem – was a just a peanut, but since it can affect other functionalities – for the record to everybody – ONE DIV REF. TO THE EMAIL : <- NEEDS TO BE CLOSED! thx once again for the great form!

  • Ey BOBA i have a little bit of a problem same as some of the people here… im not really knowledgeable enough on php and stuff… i tried downloading your demo and tried it… but what i dont get is you have placed

    which clearly the index.php doesnt exist and im having problem after i clicked the submit botton… can you explain or give me solution on this?? please?much appreaciate it if youll email me pls/? thanks

  • thanks, it helped and save me…

  • Great stuff! Thanks a lot! And Merry Christmas to you.

  • Quick update regarding the email verification code provided by WEbKILLER. I tested this script on IE, Firefox, Safari, all worked great until it was tested on the iPhone. The android and Windows phones worked great, no problem, but the email validation script breaks this form on iPhones. If you’re trying to implement this form on an iPhone, you can’t use WEbKILLER’s validation. If anyone can think of a way around this, I’d love to hear it. Thanks.

  • Liked the tutorial.

    Just FYI to make your error processing code a little neater you could create an array of errors and then add to that array when your data fails a check. YOu can use jquery’s .each function to iterate over the errors.

    Ideally, you’d also be filtering your data within your php script too, but I you’ve most likely left this out for sake of simplicity for tutorial – have mentioned it just because I didn’t see it mentioned in your tutorial :)

  • Is it possible to add a redirect to another HTML page after a pause for ’submit’ removal etc…? Something after:

    $(‘#mail_success’).fadeIn(500);

    Pause for success message and then redirect to next page…

    Thanks in advance!

  • Sure there is.
    $(“#mail_success”).fadeIn(500);
    setTimeout(function() {
    // Do the redirect or anything you want after 1.25 seconds.
    },1250);

  • Very good. Thank you.

  • Works like a charm, thank you.

  • This is what I was looking for. Thanks for sharing with all of us.

    I may customize the form according the theme of my websites and it would be best if the form will slide on scroll.

    Thank you

Leave your own!

Sponsors

freedcamp free project management

Popular Articles

fzilla file hosting