How to create PHP Contact Form with Validations in HTML and Ajax

Contact form is a best way to get feedback or contact with your visitors. Every website needs a contact form because visitors feel easy to send emails through contact forms. So I decided to share a small tutorial / Code of professional Contact form with you. Normal contact form is creating in HTML and sending emails using PHP mail function. There are different methods to prevent wrong / incomplete and invalid submissions of form by validating our form fields. We can use JavaScript and JQuery to validate our contact form. So let’s begin to creating our form now.


Demo of Contact form :

Before start to design a Contact form, see demo to take an idea what actually we are going to make.

Step 1 : Create Simple Contact form in HTML

First of all we create a simple form with basic required fields in Html. Create Contact.html file and paste this code in it.
<html>
 <head>
 <title>Contact Form in Html with Ajax Validation - webdesignseotips.com</title>
 <link rel="stylesheet" type="text/css" href="css/style.css">
 <meta name="description" content="This is a Professional Contact Form build in Html and Ajax. It validates all the form fields without refreshing the Page or form fields.">
 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
 <script type='text/javascript' src="js/validation.js"></script>
 </head>
 <body>
 <div id='container'>
 <form name="contactForm" id='contact_form' method="post" action='email.php'>
 <h2>Contact Form with Validations in HTML and Ajax</h2>
 <h3>When you Press Submit Button, Email will be send to your Entered Email Id</h3>
 <p> Your Name:
 <div id='name_error' class='error'><img src='images/error.png'>Please enter your name.</div>
 <div>
 <input type='text' name='name' id='name' placeholder="Enter Your Name Here">
 </div>
 </p>
 <p> Your Email ID:
 <div id='email_error' class='error'><img src='images/error.png'>Please enter your valid Email Address.</div>
 <div>
 <input type='text' name='email' id='email' placeholder="Enter Your Email ID Here">
 <div>
 </p>
 <p> Subject:
 <div id='subject_error' class='error'><img src='images/error.png'>Please enter Email Subject.</div>
 <div>
 <input type='text' name='subject' id='subject' placeholder="Enter Your Subject Here">
 </div>
 </p>
 <p> Your Message:
 <div id='message_error' class='error'><img src='images/error.png'>Please enter your message.</div>
 <div>
 <textarea name='message' id='message' placeholder="Enter Your Message Here"></textarea>
 </div>
 </p>
 <div id='mail_success' class='success'><img src='images/success.png'>Your message has been sent successfully.</div>
 <div id='mail_fail' class='error'><img src='images/error.png'> Sorry, error occured this time sending your message.</div>
 <p id='submit' align="center">
 <input type='submit' id='send_message' value='Submit Form'>
 <input type='reset' id='send_message' value='Reset Form'>
 </p>
</form>
 </div>
 </body>
 </html>
This is a simple form in Html but I also add some images codes in it to make it more beautiful and professional. In the head section I create links with external css style sheet file and JavaScript file. These files not created yet, we will create them later. You see we give form action to email.php file, so now we create this file to make our form working.

Step 2 : Add Sending Functionality in Contact form by Using PHP mail function

To make our form working , we need to create a PHP file where we create some variables to store fields data and then send them to the required email id using PHP mail function. So create another file with .php extension named as email.php and paste this code in the file.
<?php
 $subject = $_REQUEST['subject'] . ' Ajax HTML Contact Form : Demo'; // Subject of your email
 $to = $_REQUEST['email']; //Recipient's E-mail
$headers = 'MIME-Version: 1.0' . "\r\n";
 $headers .= "From: " . $_REQUEST['email'] . "\r\n"; // Sender's E-mail
 $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$message .= 'Name: ' . $_REQUEST['name'] . "<br>";
 $message .= $_REQUEST['message'];
if (@mail($to, $subject, $message, $headers))
 {
 // Transfer the value 'sent' to ajax function for showing success message.
 echo 'sent';
 }
 else
 {
 // Transfer the value 'failed' to ajax function for showing error message.
 echo 'failed';
 }
 ?>
Now form is ready but we add some css code to design it.

Step 3 : Design Our form using CSS

Create a new folder with name “css” and then create new file names as style.css (with .css extension). This is our external style sheet which is already linked with our form. Now Paste below Code in this file.
body {
 background:#C1CFF7;
 }
 #container {
 font-family:Arial;
 width:400px;
 padding:0;
 margin:0 auto;
 }
 #container h2 {
 font-variant:small-caps;
 font-weight:normal;
}
 #container h3 {
 font-size:14px;
 font-weight:normal;
}
 #container p {
 font-weight:normal;
}
 #container input, #container textarea {
 width:100%;
 font-family:inherit;
 padding:5px;
 border:1px solid #3399FF;
 }
 #container textarea {
 height:100px;
 border:1px solid #3399FF;
 }
 #send_message {
 width:200px !important;
 font-variant: small-caps;
 border:none;
 cursor:pointer;
 background:#3399FF;
 color:#FFFFFF;
 }
 #submit {
 text-align:left;
 }
.error {
 display: none;
 padding:10px;
 margin:0 0 5px 0;
 color: #D8000C;
 font-size:12px;
 background-color: #FFBABA;
 }
 .success {
 display: none;
 padding:10px;
 color: #044406;
 font-size:12px;
 background-color: #B7FBB9;
 }
.error img {
 vertical-align:top;
 }
You can customize its design in CSS according to your needs.

Step 4 : Validate Our Form Fields in JavaScript

Now we validate our form using JavaScript and Jquery (Libraries of JavaScript). Create another new file in Your Notepad++ or any other editor you are using and save it with extension .js and named as validation.js and save it in a new folder named as ”js” and paste this code in the validation.js file.
$(document).ready(function(){
 $('#send_message').click(function(e){
//Stop form submission & check the validation
 e.preventDefault();
// Variable declaration
 var error = false;
 var name = $('#name').val();
 var email = $('#email').val();
 var subject = $('#subject').val();
 var message = $('#message').val();
// Form field validation
 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);
 }
// If there is no validation error, next to process the mail function
 if(error == false){
 // Disable submit button just after the form processed 1st time successfully.
 $('#send_message').attr({'disabled' : 'true', 'value' : 'Sending...' });
/* Post Ajax function of jQuery to get all the data from the submission of the form as soon as the form sends the values to email.php*/
 $.post("email.php", $("#contact_form").serialize(),function(result){
 //Check the result set from email.php file.
 if(result == 'sent'){
 //If the email is sent successfully, remove the submit button
 $('#submit').remove();
 //Display the success message
 $('#mail_success').fadeIn(500);
 }else{
 //Display the error message
 $('#mail_fail').fadeIn(500);
 // Enable the submit button again
 $('#send_message').removeAttr('disabled').attr('value', 'Send The Message');
 }
 });
 }
 });
 });
We use some Jquery libraries in this file, so you must add Jquery file with it. Click here to Download file and place it in same folder (in js folder). We also use three images to make our form more beautiful and professional, which are saved in new folder named as “images” which is also attached in the source file given at the end.
Now Your form is ready to use. Simply Open Contact.html file in your browser and run it. Upload all the files on your server to test the working of this form. Although we create this form for professional use and I am giving you extra explanation of the working of form but next time we create simple form for learning form working. You can use this form for your websites. source code of all the files is given below to download.

How to create PHP Contact Form with Validations in HTML and Ajax How to create PHP Contact Form with Validations in HTML and Ajax Reviewed by Freelance Web Designer on April 28, 2020 Rating: 5

3 comments:

  1. Your article is well define thanks for sharing it. Social media marketing is the most effective and economical mode of digital marketing. Click here for social media marketing agency near me, top 10 website for freelancing work and Quora marketing services in Delhi.

    ReplyDelete
  2. Find the best and reliable Freelance Web Designer in Perth, Then you are at the right place at websmith.studio. Here you can find the best and skilled web designer for your every need.

    ReplyDelete

Powered by Blogger.