In this tutorial we will be creating a simple Ajax Contact form using jQuery and PHP. Because the best thing about Ajax is that users don’t have to reload the page every time in order to validate empty fields or to send emails, they can simply click send button and results are displayed instantly on the screen.
You can find links to demo page and downloadable sample at the bottom of this page. With few tweaks here and there, you should be able to integrate this contact form in your website. This tutorial is intended for beginners and if you have questions please do let me know by commenting.
Contact Page
When user wants to contact you, s/he will first see your contact page. It is totally up to make it look cool and presentable. In example below you can see HTML code for the form. Since we are making Ajax based contact form, we don’t need to warp the fields with <form></form>, we can simply use jQuery .val() to collect the values from the input fields.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <fieldset id="contact_form"> <legend>My Contact Form</legend> <div id="result"></div> <label for="name"><span>Name</span> <input type="text" name="name" id="name" placeholder="Enter Your Name" /> </label> <label for="email"><span>Email Address</span> <input type="text" name="email" id="email" placeholder="Enter Your Email" /> </label> <label for="phone"><span>Phone</span> <input type="text" name="phone" id="phone" placeholder="Phone Number" /> </label> <label for="message"><span>Message</span> <textarea name="message" id="message" placeholder="Enter Your Name"></textarea> </label> <label><span> </span> <button class="submit_btn" id="submit_btn">Submit</button> </label> </fieldset> |
Stylesheet
The CSS code is located in a separate file called style.css, include this file within the <head></head> section of HTML page, and modify the file as needed to make your contact page look interesting.
1 2 3 4 5 6 7 8 9 10 | #contact_form{ width:300px; padding:20px; border: 1px solid #DDD;border-radius: 5px; font-family: Arial; font-size: 11px; font-weight: bold;color: #666666; background:#FAFAFA; margin-right: auto; margin-left: auto;} #contact_form legend{font-size: 15px; color: #C9C9C9;} #contact_form label{display: block; margin-bottom:5px;} #contact_form label span{float:left; width:100px; color:#666666;} #contact_form input{height: 25px; border: 1px solid #DBDBDB; border-radius: 3px; padding-left: 4px; color: #666; width: 180px; font-family: Arial, Helvetica, sans-serif;} #contact_form textarea{border: 1px solid #DBDBDB; border-radius: 3px; padding-left: 4px;color: #666; height:100px; width: 180px; font-family: Arial, Helvetica, sans-serif;} .submit_btn { border: 1px solid #D8D8D8; padding: 5px 15px 5px 15px; color: #8D8D8D; text-shadow: 1px 1px 1px #FFF; border-radius: 3px; background: #F8F8F8;} .submit_btn:hover { background: #ECECEC;} .success{ background: #CFFFF5;padding: 10px; margin-bottom: 10px; border: 1px solid #B9ECCE; border-radius: 5px; font-weight: normal; } .error{ background: #FFDFDF; padding: 10px; margin-bottom: 10px; border: 1px solid #FFCACA; border-radius: 5px; font-weight: normal;} |
jQuery Ajax
The first thing to learn about jQuery is $(document).ready(). If you want an event to work on your page, you should call it inside the $(document).ready() function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded. So we will write all our jQuery code inside $(document).ready() function as shown in example below.
1 2 3 4 5 | <script type="text/javascript"> $(document).ready(function() { //our jquery code }); </script> |
Below is our final jQuery code for the Contact form. As you can see we have placed all code inside $(document).ready(). Right after that we have $(“#submit_btn”).click(), which gets triggered when user clicks submit button on the contact form, within this function we collect, validate and send user data to contact_me.php PHP file using jQuery $.post() method, which is a shorthand Ajax function equivalent to jQuery $.ajax(). I am sure the comment lines in the code below will help you understand the it more clearly.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | <script type="text/javascript"> $(document).ready(function() { $("#submit_btn").click(function() { //get input field values var user_name = $('input[name=name]').val(); var user_email = $('input[name=email]').val(); var user_phone = $('input[name=phone]').val(); var user_message = $('textarea[name=message]').val(); //simple validation at client's end //we simply change border color to red if empty field using .css() var proceed = true; if(user_name==""){ $('input[name=name]').css('border-color','red'); proceed = false; } if(user_email==""){ $('input[name=email]').css('border-color','red'); proceed = false; } if(user_phone=="") { $('input[name=phone]').css('border-color','red'); proceed = false; } if(user_message=="") { $('textarea[name=message]').css('border-color','red'); proceed = false; } //everything looks good! proceed... if(proceed) { //data to be sent to server post_data = {'userName':user_name, 'userEmail':user_email, 'userPhone':user_phone, 'userMessage':user_message}; //Ajax post data to server $.post('contact_me.php', post_data, function(data){ //load success massage in #result div element, with slide effect. $("#result").hide().html('<div class="success">'+data+'</div>').slideDown(); //reset values in all input fields $('#contact_form input').val(''); $('#contact_form textarea').val(''); }).fail(function(err) { //load any error data $("#result").hide().html('<div class="error">'+err.statusText+'</div>').slideDown(); }); } }); //reset previously set border colors and hide all message on .keyup() $("#contact_form input, #contact_form textarea").keyup(function() { $("#contact_form input, #contact_form textarea").css('border-color',''); $("#result").slideUp(); }); }); </script> |
Sending Email
Below is our PHP code, this file (contact_me.php) is needed to respond to contact page Ajax requests. As soon as user clicks submit button, jQuery validates empty field and sends data to this page. Here we check $_POST variables, sanitize using PHP filter_var() to remove any harmful characters in the string, thenĀ further validate them, and then send the mail to the recipient. On success, we need to output success message or the errors if it fails.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | <?php if($_POST) { //check if its an ajax request, exit if not if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') { die(); } $to_Email = "myemail@gmail.com"; //Replace with recipient email address $subject = 'Ah!! My email from Somebody out there...'; //Subject line for emails //check $_POST vars are set, exit if any missing if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userPhone"]) || !isset($_POST["userMessage"])) { die(); } //Sanitize input data using PHP filter_var(). $user_Name = filter_var($_POST["userName"], FILTER_SANITIZE_STRING); $user_Email = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL); $user_Phone = filter_var($_POST["userPhone"], FILTER_SANITIZE_STRING); $user_Message = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING); //additional php validation if(strlen($user_Name)<4) // If length is less than 4 it will throw an HTTP error. { header('HTTP/1.1 500 Name is too short or empty!'); exit(); } if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation { header('HTTP/1.1 500 Please enter a valid email!'); exit(); } if(!is_numeric($user_Phone)) //check entered data is numbers { header('HTTP/1.1 500 Only numbers allowed in phone field'); exit(); } if(strlen($user_Message)<5) //check emtpy message { header('HTTP/1.1 500 Too short message! Please enter something.'); exit(); } //proceed with PHP email. $headers = 'From: '.$user_Email.'' . "rn" . 'Reply-To: '.$user_Email.'' . "rn" . 'X-Mailer: PHP/' . phpversion(); @$sentMail = mail($to_Email, $subject, $user_Message .' -'.$user_Name, $headers); if(!$sentMail) { header('HTTP/1.1 500 Couldnot send mail! Sorry..'); exit(); }else{ echo 'Hi '.$user_Name .', Thank you for your email! '; echo 'Your email has already arrived in my Inbox, all I need to do is Check it.'; } } ?> |
That’s it! we now have a neat looking Ajax based contact form. I do want to see it working live in one of your website, so if you are using this example, please do comment and share your links here and good luck!

Helpful tutorial
thank you
please sir i tried it but not working can you help me
The Phone number does not appear in final message. Other wise it works.
How would you handle radio button choices in your form?
How do i automatically open the submission form when the page is completely loaded?
Just updated the tutorial, you no longer need to open it on page load.
The form appears to work, but I never receive the email. For the recipient, I’ve tried a hotmail.com address as well as my email address at sbcc.edu. Thanks in advance for any and all assistance!
Never mind, I’m an idiot. I’m on a free plan with my hosting company and they block all php emails. Doh!
Please sir i am new in PHP i tried to send an email according your given method but could not do so when i clicked on submit button there is an error message (“mail could’ t send”) i will be very thankful to you if you’ ll help me